如何根据另一个数组中的元素拆分数组

Xio*_*ion 6 javascript arrays jquery

我有两个数组:array1和array2.因此,array1将根据内部元素array2进行拆分.例如:

array1["1","2","3","4","5","6"]
array2["2","5"]
Run Code Online (Sandbox Code Playgroud)

我的代码:

var prev = 0;
newArray = []; 
for (var ii in array2) {
    var index = array1.indexOf(array2[ii]);

    if (index != prev) {
        newArray.push(array1.slice(prev, index));
        prev = index;
    }
 }
 newArray.push(array1.slice(prev));
Run Code Online (Sandbox Code Playgroud)

结果将是:

["1"],["2","3","4"],["5","6"]
Run Code Online (Sandbox Code Playgroud)

但是现在我面临的问题是array1的元素可能没有按顺序排列.例如:["1","5","3","4","2","6"].所以根据我的代码,它将错误地拆分array1,因为array2中的第一个元素是"2",所以它已经将array1拆分为两个["1","5","3","4"],["2","6"].接下来当"5"时,它找不到它.

预期的结果是:["1"],["5","3","4"],["2","6"]

那么如何基于array2拆分array1,无论array1是按升序,降序还是随机顺序.对不起,我的英语不好.希望你们能理解.

Arm*_*ran 9

SetArray.prototype.reduce()获取更多信息.

// Split Up.
const splitup = (array, keys) => (set => array.reduce((output, value) => {
  if (set.has(value)) output.push([value]) // Split.
  else output[output.length-1].push(value) // Append.
  return output
}, [[]]))(new Set(keys))

// Output.
const output1 = splitup(["1","2","3","4","5","6"], ["2","5"])
console.log(...output1) // ["1"],["2","3","4"],["5","6"]
const output2 = splitup(["1","5","3","4","2","6"], ["2","5"])
console.log(...output2) // ["1"],["5","3","4"],["2","6"]
Run Code Online (Sandbox Code Playgroud)

  • 如果代码(主要是箭头函数)不那么简洁和可读性,我的首选答案.还是+1.就像它读取`if(set.has(value))`的方式一样......你不能再像伪代码那样制作JavaScript了.做得好 (2认同)

H77*_*H77 1

尝试这个。它循环array1并将每个项目推送到临时数组中。当在临时数组中找到该项目时,array2将其推送到最终数组中,然后重置。

var array1 = ["1", "5", "3", "4", "2", "6"];
var array2 = ["2", "5"];

var newArray = [];
var currArray = [];

for (let i = 0; i < array1.length; i++) {

  // Item exists in array2. Add to newArray and reset currArray
  if (i > 0 && array2.includes(array1[i])) {
    newArray.push(currArray);
    currArray = [];
  }

  currArray.push(array1[i]);
}

newArray.push(currArray); // Add final currArray to newArray

console.log(newArray); // print result
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果索引顺序很重要(如您的情况),最好不要使用for..in迭代数组,因为它不会以任何特定顺序返回索引。更多信息请点击这里

  • 是的。“O(M*N) 复杂度”是使用 [`Array.prototype.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects) 的结果/Array/includes) 在 [`for 循环`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) 中。 (2认同)