Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Array separate odd and even to array of objects Javascript

I have a question.

I have a Array like below

WorkList1 = ["Monday", "running", "Tuesday", "swimming", "Wednesday", "riding"]

I expect change it like

WorkList2 = [{ "day": "Monday", "exercise": "running" }, 
             { "day": "Tuesday", "exercise": "swimming" },
             { "day": "Wednesday", "exercise": "riding" }]

but it seems got some Error, this is my code.

const WorkList2 = [];
const object = { "day": '', "exercise": '' };
for (let i = 0; i < WorkList1.length; i += 1) {
  if (i % 2 === 0) {
    object['day'] = i;
  } else {
    object['exercise'] = i;
  }
  WorkList2.push(object);
}

I have read some thread about Array but I still have some trouble..... Could somebody help me to figure it out? thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

1) You are assigning the value as array index i

object['day'] = i; 

2) It will have as many objects as there are in WorkList1.

You have to skip the insertion at every odd index. What you can do is just loop over the array and increment it by 2 instead of 1 and push data value as WorkList1[i] and exercise as WorkList1[i + 1]

const WorkList1 = [
  "Monday",
  "running",
  "Tuesday",
  "swimming",
  "Wednesday",
  "riding",
];

const WorkList2 = [];

for (let i = 0; i < WorkList1.length; i += 2) {
  WorkList2.push({
    day: WorkList1[i],
    exercise: WorkList1[i + 1],
  });
}

console.log(WorkList2);

You can also try the second solution

const WorkList1 = [
  "Monday",
  "running",
  "Tuesday",
  "swimming",
  "Wednesday",
  "riding",
];

const WorkList2 = [];

for (let i = 0; i < WorkList1.length; i += 1) {
  if (i % 2 === 0) {
    WorkList2.push({
      day: WorkList1[i]
    });
  } else {
    const lastObj = WorkList2[WorkList2.length - 1];
    lastObj.exercise = WorkList1[i];
  }
}

console.log(WorkList2);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!