Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push the contents of array into another array without looping

Here's a simple piece of JavaScript where I want to add the contents of orders.foo and orders2.foo to a single-dimensional ordersArr.

let _ = require('underscore');

let ordersArr = [];
let orders = {
    foo: [
        {x: 1, b: 2},
        {y: 1, c: 3},
        {a: 2, d: 4}
    ]
}

ordersArr = _.map(orders.foo, order => order)

orders2 = {
        foo: [
                {x: 2, b: 3},
                {y: 5, c: 4},
                {a: 3, d: 6}
        ]
}


let tOrders = _.map(orders2.foo, order => order);
ordersArr.push(tOrders)

console.log(ordersArr);

The problem with this code is that push in this case creates a multi-dimensional array:

Output

[
  { x: 1, b: 2 },
  { y: 1, c: 3 },
  { a: 2, d: 4 },
  [ { x: 2, b: 3 }, { y: 5, c: 4 }, { a: 3, d: 6 } ]
]

How do I iterate the contents of orders.foo and orders2.foo and have their results as one single dimension array?

like image 843
randombits Avatar asked Dec 03 '22 09:12

randombits


2 Answers

You can spread the content of both arrays into the new array

const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
// prints [1,2,3,4,5,6]

Spreading arr2 into arr1 also works.

arr1.push(...arr2);
console.log(arr1);
// prints [1,2,3,4,5,6]

So changing

ordersArr.push(tOrders)

to

ordersArr.push(...tOrders);

should work.

For a full answer:

let ordersArr = [];
let orders = {
    foo: [
        {x: 1, b: 2},
        {y: 1, c: 3},
        {a: 2, d: 4}
    ]
}

orders2 = {
        foo: [
                {x: 2, b: 3},
                {y: 5, c: 4},
                {a: 3, d: 6}
        ]
}

ordersArr.push(...orders.foo, ...orders2.foo);
like image 109
Leshawn Rice Avatar answered Dec 04 '22 21:12

Leshawn Rice


Using underscore _.flatten:

const 
  orders = { foo: [ {x: 1, b: 2}, {y: 1, c: 3}, {a: 2, d: 4} ] },
  orders2 = { foo: [ {x: 2, b: 3}, {y: 5, c: 4}, {a: 3, d: 6} ] };
  
const ordersArr = _.flatten([orders.foo, orders2.foo]);

console.log(ordersArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>

Using javascript spread operator:

const 
  orders = { foo: [ {x: 1, b: 2}, {y: 1, c: 3}, {a: 2, d: 4} ] },
  orders2 = { foo: [ {x: 2, b: 3}, {y: 5, c: 4}, {a: 3, d: 6} ] };
  
const ordersArr = [...orders.foo, ...orders2.foo];

console.log(ordersArr);

Using javascript Array#concat:

const 
  orders = { foo: [ {x: 1, b: 2}, {y: 1, c: 3}, {a: 2, d: 4} ] },
  orders2 = { foo: [ {x: 2, b: 3}, {y: 5, c: 4}, {a: 3, d: 6} ] };
  
const ordersArr = orders.foo.concat(orders2.foo);

console.log(ordersArr);
like image 44
Majed Badawi Avatar answered Dec 04 '22 22:12

Majed Badawi