简体   繁体   中英

Convert every nth element of an array to an object in javascript

I'd like to convert:

var people = [1,"Shaw","Tanzania",2,"Nelson","Kazakhstan",3,"Garcia","Madagascar"]

into:

var rows = [
    [1, "Shaw", "Tanzania"],
    [2, "Nelson", "Kazakhstan"],
    [3, "Garcia", "Madagascar"]
];

I've seen this answer to a similar question, but I don't understand how that works and extend it to every nth element

Use a for loop with Array#slice . You iterate the original array using the require chunk size as the step. On each iteration you slice the relevant part from the original array (slice doesn't mutate the array), and push it into the result array.

 var people = [1,"Shaw","Tanzania",2,"Nelson","Kazakhstan",3,"Garcia","Madagascar"]; var result = []; var chunkSize = 3; for(var i = 0; i < people.length; i+= chunkSize) { result.push(people.slice(i, i + chunkSize)); } console.log(result); 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM