Reputation: 165
If I have an array such as this:
let arr = [{name: "Cool", subject_schedule: ["So","3610A", "USA", "1010"]}, {name: "Lots", subject_schedule: ["Dog","1310A", "CAN", "2020"]} ];
How can I make it so the "subject_schedule" property in each of the objects in the array is combined into pairs such as:
let result = [{name: "Cool", subject_schedule: ["So 3610A", "USA 1010"]}, {name: "Lots", subject_schedule: ["Dog 1310A", "CAN 2020"]} ];
Upvotes: 0
Views: 43
Reputation: 3302
You could use Array.prototype.map()
method and for pairing subject_schedule array use a simple recursive function. Map method returns a new array by calling the provided function for each item of the array.
const data = [
{ name: 'Cool', subject_schedule: ['So', '3610A', 'USA', '1010'] },
{ name: 'Lots', subject_schedule: ['Dog', '1310A', 'CAN', '2020'] },
];
const makePair = (arr, result = []) => {
if (arr.length === 0) return result;
result.push(arr.slice(0, 2).join(' '));
return makePair(arr.slice(2), result);
};
const ret = data.map((x) => ({
...x,
subject_schedule: makePair(x.subject_schedule),
}));
console.log(ret);
Upvotes: 2