简体   繁体   中英

Looping through a nested array in JavaScript

Presently I have a multidimensional array that I want to loop over. All I want is to push the inner elements to an empty array. But What I'm getting is totally different from the expected output.

All have done so far below

 const prices = [ [2, 20], [7, 50], [12, 100], [17, 40], [22, 32], [27, 25 ] ]; function addItemToCart() { let new_items = [] // I want this array to be [2, 7, 12, 17, 22, 27] // looping outer array elements for(let i = 0; i < prices.length; i++) { for(let j = 0; j < prices[i].length; j++) { new_items.push(prices[i][j]) console.log(new_items); } } } addItemToCart()

Use map: const newItems = prices.map(price => price[0])

Do you want to completely flatten your array, or just take the first item from each inner array and copy that to the new array?

If you want to flatten it completely, you can do it like this:

const newArray = prices.reduce((res, arr) => [...res, ...arr], []);

If you only want the first item from each inner array, I would recommend the solution that Konstantin suggested.

You don't need loops for that:

 const prices = [ [2, 20], [7, 50], [12, 100], [17, 40], [22, 32], [27, 25 ] ]; const toAdd = [].concat.apply([], prices); console.log(toAdd);

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