首页 > 解决方案 > 基于第二个阵列将阵列划分为多个部分

问题描述

两个数组,一个包含对象,另一个包含字符串值,基于第二个数组值,希望将第一个数组转换为多个数组。就我而言,它是两个。

    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"} ]

标签: javascriptarrays

解决方案


您的代码的一些问题是:

  1. 比较相同的数组元素if (arr1[j].key === arr1[i])
  2. 在找到匹配元素并立即将下一个元素插入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);


推荐阅读