我有两个数组:array1和array2。因此,array1将根据内部元素array2进行拆分。例如:
array1["1","2","3","4","5","6"]
array2["2","5"]
我的代码:
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));
结果将是:
["1"],["2","3","4"],["5","6"]
但是现在我面临的问题是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是升序,降序还是随机顺序。对不起,我的英语不好。希望你们能理解。
答案 0 :(得分:9)
有关详细信息,请参阅Set
和Array.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"]

答案 1 :(得分: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
另一方面,如果索引顺序很重要(如在您的情况下那样),最好不要使用for..in
来遍历数组,因为它不会以任何特定顺序返回索引。更多信息here。