如何基于另一个数组分离数组

时间:2017-12-23 07:47:58

标签: javascript arrays

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

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个新数组,每个数组只有一个项目。

3 个答案:

答案 0 :(得分:2)

以下是开始和实现的方式

&#13;
&#13;
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);
&#13;
&#13;
&#13;

&#13;
&#13;
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);
&#13;
&#13;
&#13;

还有动态变量

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以采用单个循环并查找分离元素并使用块构建新数组。稍后将其余部分添加到结果中。

此版本适用于阵列中的重复项以进行拆分。

function group(array, starts) {
    var index = 0,
        result = [];

    starts.forEach(function (v) {
        result.push(array.slice(index, index = array.indexOf(v, index)));
    });
    result.push(array.slice(index));
    return result;
}

console.log(group(["str1", "str2", "str3", "str4", "str5", "str6"], ["str2", "str5"]));
console.log(group(["str1", "str2", "str3", "str4", "str5", "str6"], ["str2", "str3"]));
console.log(group(["str1", "str2", "str3", "str4", "str5", "str6"], []));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

使用ES6 - 从read_pipe项中创建Set。使用Array#reduce迭代array2。如果没有子数组,或者在array2 Set中找到当前字符串(使用Set#has),则添加一个新的子数组。始终将当前字符串推送到最后一个子数组。

array1