peter flanagan
peter flanagan

Reputation: 9800

based on index of array add items to array in object

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

Upvotes: 0

Views: 39

Answers (3)

eltonkamami
eltonkamami

Reputation: 5190

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

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371029

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

Upvotes: 2

user835611
user835611

Reputation: 2366

You want

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

Upvotes: 1

Related Questions