简体   繁体   中英

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]]. Is it possible to do without for loop?

You can use slice and push method like this

 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

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

https://lodash.com/docs/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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