Reputation: 1338
I want so extract two values from an array holding both of the mentioned values in a single property of an object.
Included you can find my code as well as a Stackblitz project.
I don´t know what to do inside the .map()
call in order to split the coords property into two x and y arrays.
Stackblitz: https://stackblitz.com/edit/ckpxyz?file=index.ts
class MyClass {
coords: number[];
constructor(coords: number[]) {
this.coords = coords;
}
}
var myList: MyClass[] = [
new MyClass([1,2]),
new MyClass([3,4]),
new MyClass([5,6]),
new MyClass([7,8]),
new MyClass([9,10]),
]
myList.map((myObj: MyClass) => {
console.log(myObj.coords[0], myObj.coords[1]);
// what to do here to split the array?
});
// GOAL:
// x:number[] = [1,3,5,7,9];
// y:number[] = [2,4,6,8,10];
Upvotes: 0
Views: 1057
Reputation: 66123
You can use ES6 array destructuring to do that for you. Instead of using Array.prototype.map
, you should use Array.prototype.reduce
because you can iterate through the entire myList
once, and then store the x
and y
coordinates in separate sub-arrays:
const [x, y] = myList.reduce((accumulator, currentValue) => {
// Unpack/destructure nested arrays
const [x, y] = accumulator;
// Push coordinates into sub-arrays
x.push(currentValue.coords[0]);
y.push(currentValue.coords[1]);
// Repack and return updated accumulated values
return [x, y];
}, [[], []] as [number[], number[]]);
In the code above, you basically initialise the reduction process with an array that has the shape of a tuple containing array of numbers, i.e. [number[], number[]]
, where the first array stores your x coordinates and the second stores your y coordinates.
In each iteration of the reduce, you unpack/destructure the subarrays using const [x, y] = <currentValueReference>
. Then, you simply push coords[0]
(which is your x coordinate) and coords[1]
(which is your y coordinate) into the unpacked arrays.
Then, you repack the arrays by simple returning [x, y]
.
See proof-of-concept example here.
Upvotes: 2