0

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"]} ];

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

what a nice way to use makePair recursion here. good thought. without looking at the solution, i gave it a try and ended up with almost similar to yours without recursion. but, yours is very neat. arr.map((item) => { const{ subject_schedule } = item; const combined_subject_schedule = []; for(i = 0; i<subject_schedule.length; i+=2) { combined_subject_schedule.push(subject_schedule.slice(i, i+2).join(' ')); } return {...item, subject_schedule: combined_subject_schedule} })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.