1

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!

1 Answer 1

2

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

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

Comments

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.