javascript - 基于第二个阵列将阵列划分为多个部分
问题描述
两个数组,一个包含对象,另一个包含字符串值,基于第二个数组值,希望将第一个数组转换为多个数组。就我而言,它是两个。
let arr1= [{"key": "English","code": "en"}, {"key": "Arabic","code": "ar"},
{"key": "Chinese (traditional)","code": "zh"},
{"key": "Czech", "code": "cs"},
{"key": "Dutch","code": "nl"},{"key": "Finnish","code": "fi"}]
let arr2 = ["English", "Dutch", "Finnish"];
let completed =[];
let optional =[];
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if (arr1[j].key === arr1[i]) {
completed.push(arr1[j])
}else{
optional.push(arr1[j])
}
}
}
以这样的输出为目标
completed=[{"key": "English","code": "en"},{"key": "Dutch","code": "nl"},
{"key": "Finnish","code": "fi"}]
optional=[{"key": "Arabic","code": "ar"},{"key": "Chinese (traditional)","code": "zh"},
{"key": "Czech", "code": "cs"} ]
解决方案
您的代码的一些问题是:
- 比较相同的数组元素
if (arr1[j].key === arr1[i])
。 - 在找到匹配元素并立即将下一个元素插入
optional
数组时不会打破循环。
解决这些问题,您的代码将如下所示:
let arr1 = [{ "key": "English", "code": "en" }, { "key": "Arabic", "code": "ar" }, { "key": "Chinese (traditional)", "code": "zh" }, { "key": "Czech", "code": "cs" }, { "key": "Dutch", "code": "nl" }, { "key": "Finnish", "code": "fi" } ] ;
let arr2 = ["English", "Dutch", "Finnish"];
let completed = [];
let optional = [];
for (let i = 0; i < arr1.length; i++) {
let found = false;
for (let j = 0; j < arr2.length; j++) {
if (arr1[i].key === arr2[j]) {
completed.push(arr1[i]);
found = true;
break;
}
}
if (!found) {
optional.push(arr1[i]);
}
}
console.log("Completed: ", completed);
console.log("Optional: ", optional);
另一种更简单的方法是使用Array.filter()和Array.includes()。
let arr1 = [{ "key": "English", "code": "en" }, { "key": "Arabic", "code": "ar" }, { "key": "Chinese (traditional)", "code": "zh" }, { "key": "Czech", "code": "cs" }, { "key": "Dutch", "code": "nl" }, { "key": "Finnish", "code": "fi" } ] ;
let arr2 = ["English", "Dutch", "Finnish"];
let completed = arr1.filter(item => arr2.includes(item.key));
let optional = arr1.filter(item => !arr2.includes(item.key));
console.log("Completed: ", completed);
console.log("Optional: ", optional);
推荐阅读
- javascript - 输入以 django 形式收到的有效日期错误
- assembly - 当我们将一个 16 位数字除以一个 8 位 1 时会发生什么?
- javascript - JavaScript - 需要多维数组?
- asp.net-core-webapi - 使用 Simple.Odata.Client 查询查询 Dynamics CRM (微服务 - Web Api net core 2.2)
- django - 如果用户登录,则基于 Django 类的视图 TemplateView 执行重定向
- php - 正确创建单页 WordPress 主题
- mongodb - Robo 3T:在将集合导出到 JSON 时填充 Javascript 函数调用的实际值
- javascript - 安装模块与使用其 url 包含模块之间的主要区别是什么?
- php - PHP:如何“空”一个类结果
- amazon-s3 - PIXI.JS:将 Origin 从 API Gateway 切换到 NGINX 后 Cloudfront+S3 出现 CORS 问题