简体   繁体   English

JavaScript按条件拆分和合并数组

[英]JavaScript split and merge arrays by conditions

I have an array like [a, b, c, d] and I want to split it into 2 arrays like [a, b] and [c, d] and then merge it to have final result like [[a, b],[c, d]]. 我有一个像[a,b,c,d]的数组,我想把它分成2个像[a,b]和[c,d]的数组,然后将其合并成具有[[a,b]的最终结果,[c,d]]。 Is it possible to do without for loop? 是否可以不使用for循环?

You can use slice and push method like this 您可以像这样使用slicepush方法

 var arr = ['a', 'b', 'c', 'd']; let index = 2; let result = []; result.push(arr.slice(0, index)); result.push(arr.slice(index)) console.log(result); 

yes without loop you can do this But you should know at what index you have to split the array. 是的,没有循环,您可以执行此操作,但是您应该知道必须在哪个索引处拆分数组。

 var arr = ['a', 'b', 'c', 'd']; var indexToSplit = arr.indexOf('c'); var first = arr.slice(0, indexToSplit); var second = arr.slice(indexToSplit + 1); var final = [first, second] console.log(final); 

let arr = [0, 1, 9, 10, 8];
    let arr2 = arr.slice(1,3);
    let resultArr = [];

    if(arr2[1] > 1){
    resultArr.push(99); 
    }
else{
    resultArr.push(100); 

}
    console.log(resultArr)

You might like something like this: 您可能会喜欢这样的东西:


a = 8;
b = { some: 'say'};
c = 'life';
d = true;

let o = {
    'a': [a, b, c, d],
    'a1': [],
    'a2': []
}
nSwitchBefore = 2;

o.a.forEach(function(item, i) {
   i < nSwitchBefore ? this.a1.push(item) : this.a2.push(item) ;
}.bind(o));

console.log(o);

Within the function block there is room for extra handling your array items. 在功能块中,还有空间可以额外处理数组项。 Like filtering or special treatment of certain types, using all conditions you want. 使用所需的所有条件,例如过滤或对某些类型进行特殊处理。

I found another solution for this issue, without writing loops Lodash Chunk does this logic 我找到了解决此问题的另一种方法,而没有编写循环Lodash Chunk做到了这一逻辑

_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]

https://lodash.com/docs/ https://lodash.com/docs/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM