简体   繁体   中英

How can I form an object with 2 array efficiently

I have 2 arrays

const x = [0, 1, 2, 3, 4, 5]
const y = [6, 7, 8, 9, 10, 11]

I'm trying to combine the two array into an array of objects such that it becomes:

[{x: 0, y: 6}, {x: 1, y: 7}, {x: 2, y: 8}, {x: 3, y: 9}, {x: 4, y: 10}, {x: 5, y: 11}]

Currently what I did was to loop the length of one of the arrays then push the object to the new array.

let newArray = []
for(i = 0; i < x.length; i++) {
   newArray.push({x: x[i], y: y[i]})
}

Just wondering if there is a more efficient way to do this, thanks!

You can use map to do the same thing.

 const x = [0, 1, 2, 3, 4, 5] const y = [6, 7, 8, 9, 10, 11] const newArray = x.map((number, index) => ({x: number, y: y[index]})); console.log(newArray)

And here is the same thing using 'reducer'

 const x = [0, 1, 2, 3, 4, 5] const y = [6, 7, 8, 9, 10, 11] const newArray = x.reduce((arr, n, index) => { arr.push({x: n, y: y[index]}); return arr; }, []) console.log(newArray)

You could go over an object and get the entries for having an array of objects.

This approach works as well for more arrays.

 const x = [0, 1, 2, 3, 4, 5], y = [6, 7, 8, 9, 10, 11], result = Object.entries({ x, y }).reduce((r, [k, a]) => a.map((v, i) => ({... r[i], [k]: v })), []); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Your solution is good. Another way using .map :

 const getCoordinates = (xCoordinates=[], yCoordinates=[]) => xCoordinates.map((x,index) => ({x, y:yCoordinates[index]})); console.log( getCoordinates([0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]) );

Another way using for-loop (to handle different list sizes):

 const getCoordinates = (xCoordinates=[], yCoordinates=[]) => { const coordinates = []; for(let i = 0, j = 0; i < xCoordinates.length && j < yCoordinates.length; i++, j++) coordinates.push({x:xCoordinates[i], y:yCoordinates[i]}); return coordinates; } console.log( getCoordinates([0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]) );

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