gpt4 book ai didi

javascript - 如何根据另一个数组分离一个数组

转载 作者:行者123 更新时间:2023-11-30 14:52:09 26 4
gpt4 key购买 nike

所以我有两个这样的数组。

var array1 = ["str1", "str2", "str3", "str4", "str5", "str6"];

如何根据 array2 中的元素拆分 array1,以便结果变成这样并存储在 3 个数组中(不总是 3,取决于 array2 的项目)?

var array2 = ["str2","str5"];
// Case1 result
// newArr1=["str1"]
// newArr2=["str2","str3","str4"]
// newArr3=["str5","str6"]

var array2 = ["str2","str3"];
//Case2 result
// newArr1=["str1"]
// newArr2=["str2"]
// newArr3=["str3","str4""str5","str6"]

我试过了,但我不知道如何达到上面的结果。

for (i = 0; i < array2.length; i++) {
newArr = array1.splice(0, array1.indexOf(array2[i]));
}

array2 充当断点。因此,如果 array2 包含 array1 的所有元素。它应该生成 6 个新数组,每个数组只有一项。

最佳答案

这里是开始和实现你想要的方式

var array1 = ["str1", "str2", "str3", "str4", "str5", "str6"];
var newArray = [];
var array2 = ["str1", "str2", "str3", "str4", "str5", "str6"];
var prev = 0;
for(let i in array2){
var index = array1.indexOf(array2[i]);
if(index != prev){
newArray.push(array1.slice(prev,index));
prev = index;
}
}
newArray.push(array1.slice(prev));
console.log(newArray);

var array1 = ["str1", "str2", "str3", "str4", "str5", "str6"];
var newArray = [];
var array2 = ["str2", "str5"];
var prev = 0;
for(let i in array2){
var index = array1.indexOf(array2[i]);
if(index != prev){
newArray.push(array1.slice(prev,index));
prev = index;
}
}
newArray.push(array1.slice(prev));
console.log(newArray);

还有动态变量

var array1 = ["str1", "str2", "str3", "str4", "str5", "str6"];
var count = 1;
var array2 = ["str2", "str5"];
var prev = 0;
for(let i in array2){
var index = array1.indexOf(array2[i]);
if(index != prev){
window['newArray'+ count++] = array1.slice(prev,index);
prev = index;
}
}
window['newArray'+ count++] = array1.slice(prev);
console.log('newArray1 : ',newArray1);
console.log('newArray2 : ',newArray2);
console.log('newArray3 : ',newArray3);

关于javascript - 如何根据另一个数组分离一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47950770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com