Dr.Dough
Dr.Dough

Reputation: 165

Remove Alternating Commas from An Object contained in an Array in JavaScript

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

Answers (1)

phi-rakib
phi-rakib

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

Related Questions