0

I am scraping a website and have an array of numbers that I am looping over:

const arr = [1,2,3,1,2,4,5,6,7];

they correspond to win/lose/draw for different teams:

i.e.

1st item in array is won, second is draw, third is loss, fourth is won, fifth is draw, sixth is loss etc.

How can I loop through these so I have something like the following:

const teams = [{
  won: 1,
  draw: 2,
  lost: 3
 },{ 
  won: 1,
  draw: 2,
  lost: 4
 },{
  won: 5,
  draw: 6,
  lost: 7
}];

I tried something like the following but it didn't work as I expected.

   const arr = [1, 2, 3, 1, 2, 4, 5, 6, 7];

const newArr = [];

arr.forEach((item, index => {
   if (index % 0 === 0) {
     newArr.push({
       won: item
     });

   } else if (index % 1 === 0) {
     newArr.push({
       draw: item
     });
   } else {
     newArr.push({
       lost: item
     });
    }
 });

2
  • 1
    You need to read up on what % does, index % 1 means the remainder when index is divided by 1, which is always 0 (for non-negative integers). Commented Jun 10, 2018 at 21:50
  • Start with a syntax free example "Uncaught SyntaxError: missing ) after argument list" Commented Jun 10, 2018 at 21:53

3 Answers 3

2

Unfortunately, using the array methods like forEach won't work well because you need to consolidate multiple array elements into a single object. It's possible, but it would be a bit confusing. It might be clearer if you use a for loop:

const arr = [1,2,3,1,2,4,5,6,7];
const teams = [];
for (let i = 0; i < arr.length; i += 3) {
  teams.push({
    won: arr[i],
    draw: arr[i + 1],
    lost: arr[i + 2],
  });
}

console.log(teams);

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

1 Comment

+1. Alternatively, use a inChunksOf3 helper function and loop over the results of that.
1

You want

index % 3 === 0; // 0, 3, 6, ...
index % 3 === 1; // 1, 4, 7, ...
index % 3 === 2; // 2, 5, 8, ...

1 Comment

On right track or not, produce the final example desired for better answer.
1

You can loop over your array but only consider every third element by using i+=3:

let teams = [];
function teamStats(won, draw, lost){
  return {won, draw, lost};
}
for(let i = 0; i < arr.length; i+=3){
  teams.push(teamStats(arr[i], arr[i+1], arr[i+2]));
}

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.