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:
ie
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 }); } });
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);
You want
index % 3 === 0; // 0, 3, 6, ...
index % 3 === 1; // 1, 4, 7, ...
index % 3 === 2; // 2, 5, 8, ...
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]));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.