Suppose, we have an array of objects like this −
const arr = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6}
];We are required to write a JavaScript function that takes in one such array of objects. The function should then map this array to an array of Number literals like this −
const output = [1, 2, 3, 4, 5, 6];
Example
const arr = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6}
];
const pushToArray = (arr = []) => {
const result = arr.reduce((acc, obj) => {
acc.push(obj.a);
acc.push(obj.b);
return acc;
}, []);
return result;
};
console.log(pushToArray(arr));Output
And the output in the console will be −
[ 1, 2, 3, 4, 5, 6 ]