0

I have an array which contains arrays of objects. Here is an example:

[ [{name: Alex, number: 2}, {name: Bill, number: 3}],  [{name: John, number: 5}, {name: Aston, number: 7}]]

I want to create another array which contains all the objects of the above array of arrays like this:

[{name: Alex, number: 2}, {name: Bill, number: 3}, {name: John, number: 5}, {name: Aston, number: 7}] 

I wrote the code below:

const productsInfoArray = [];
const productsRecords = customerContacts.map(i => i.products).map(product => {
  product.map(i => productsInfoArray.push(i));
  return productsInfoArray;
});

But when I console.log(productsRecords) an array of array is being returned which contains all the info. The problem is that this array contains the 12 times the wanted array because customerContacts length is 12

mplungjan
  • 169,008
  • 28
  • 173
  • 236
RamAlx
  • 6,976
  • 23
  • 58
  • 106

4 Answers4

5

You can flatten an array by spreading into Array.concat():

const data = [ [{name: 'Alex', number: 2}, {name: 'Bill', number: 3}],  [{name: 'John', number: 5}, {name: 'Aston', number: 7}]]

const productsRecords = [].concat(...data)

console.log(productsRecords)

Or by using Array.reduce(), and concat for very large arrays, since spread is not stack safe:

const data = [ [{name: 'Alex', number: 2}, {name: 'Bill', number: 3}],  [{name: 'John', number: 5}, {name: 'Aston', number: 7}]]

const productsRecords = data.reduce((r, a) => r.concat(a), [])

console.log(productsRecords)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

this problem has been resolved

var arrToConvert = [ [{name: "Alex", number: 2}, {name: "Bill", number: 3}],  [{name: "John", number: 5}, {name: "Aston", number: 7}]]
var newArr = [];


for(var i = 0; i < arrToConvert.length; i++)
{
    newArr = newArr.concat(arrToConvert[i]);
}

console.log(newArr);
Whoiskp
  • 444
  • 4
  • 7
1
var data=[[{name: 'Alex', number: 2}, {name: 'Bill', number: 3}],  [{name: 'John', number: 5}, {name: 'Aston', number: 7}]];
var copy = [];
for(var i=0;i<data.length;i++){
  copy = copy.concat(data[i]);
}
console.log(copy);
Harish Krishnan
  • 1,693
  • 4
  • 17
  • 25
1

If you want to use a code that is more self explanatory then you can use the traditional way so that in future if you want add more complex logic then it will be easy for you to modify it.

var inputArray =[ [{name: "Alex", number: 2}, {name: "Bill", number: 3}],  [{name: "John", number: 5}, {name: "Aston", number: 7}]];

var outputArray = [];

//loop over the array or arrays
inputArray.forEach((item)=>{
  //loop over each array inside inputArray
  item.forEach((obj) => {
     //push each individual object in a new array
     outputArray.push(obj);
  });
});

console.log(outputArray);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62