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

0

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.