我需要根据从另一个数组中搜索元素将数组拆分为N个数组

问题描述 投票:-2回答:2

我需要根据从另一个数组中搜索元素来将一个数组拆分为N个数组。

考虑此场景

var test = ["1","2","3","env","6","7","8","uat","2344","wersdf","sdfs"];
var test2=["env","uat"];

现在我想要一张类似的地图

{
env:["6","7","8"],
uat:["2344","wersdf","sdfs"]
}

请注意,test2和test1中的数组项是动态的。但是在测试数组中,两个test2值不会一个接一个地出现,它们之间会有一些项目。

javascript jquery arrays typescript angular7
2个回答
2
投票

您可以使用Array#Reduce

  1. 首先迭代test2数组并匹配test的索引
  2. 然后使用起始值为ind+1的forloop。它将针对定界符的下一个参数
  3. 使用acc[b].push()将值传递到数组后
  4. 然后在else条件下使用test2.indexOf(test[i]) == -1检测下一个定界符。这时您需要中断语句。然后再次启动test2的第二个参数

function maper(test, test2) {
  return test2.reduce((acc, b) => {
    let ind = test.indexOf(b); //detect starting index of delimiter
    if (ind > -1) {
      acc[b] = acc[b] || []; 
      for (var i = ind+1; i < test.length; i++) {
        if (test2.indexOf(test[i]) == -1) { //detet next delimiter reach
          acc[b].push(test[i])
        }else{
         break;
        }
      }
    }
    return acc
  }, {})
  
}

var test = ["1", "2", "3", "env", "6", "7", "8", "uat", "2344", "wersdf", "sdfs"];
var test2 = ["env", "uat"];

console.log(maper(test, test2))

1
投票

var test = ["1","2","3","env","6","7","8","uat","2344","wersdf","sdfs"];
var test2=["env","uat"];
 
var indexArray = [];

test2.map(key=>{
var index = test.indexOf(key);
  indexArray.push(index);
})
 
var obj = {};
for(var i = 0; i<indexArray.length; i++){

  var part = test.slice(indexArray[i]+1, indexArray[i+1]);
   obj = {...obj,[test2[i]]: [ ...part]};
}
console.log("obj = ", obj);
© www.soinside.com 2019 - 2024. All rights reserved.