简体   繁体   中英

Evenly chunk an array using lodash

I got countries.json which I am chunking to display in 4 columns as per specification.

I am looking at a solution where the array elements are evenly distributed to all four arrays.

Sample JSFIDDLE https://jsfiddle.net/5tkjLs7b/

If I remove one country from the json data, I will end-up with 6 arrays. But the expected is only 4 arrays.

Also the data should be evenly distributed.

Example : I am getting 63 items*4 arrays + 3 items*1 array for full country.json.

var countries = [ 
  {"name": "Afghanistan", "code": "AF"}, 
  {"name": "Åland Islands", "code": "AX"}, 
  {"name": "Albania", "code": "AL"}, 
  {"name": "Algeria", "code": "DZ"}, 
  {"name": "American Samoa", "code": "AS"}, 
  {"name": "AndorrA", "code": "AD"}, 
  {"name": "Angola", "code": "AO"}, 
  {"name": "Anguilla", "code": "AI"}, 
  {"name": "Antarctica", "code": "AQ"}, 
  {"name": "Antigua and Barbuda", "code": "AG"}, 
  {"name": "Argentina", "code": "AR"}, 
  {"name": "Armenia", "code": "AM"}];

  chunkedCountries = _.chunk(countries, countries.length/4)
  console.log(chunkedCountries);

You can use for loop and slice() to get desired result.

 var countries = [ {"name": "Afghanistan", "code": "AF"}, {"name": "Åland Islands", "code": "AX"}, {"name": "Albania", "code": "AL"}, {"name": "Algeria", "code": "DZ"}, {"name": "American Samoa", "code": "AS"}, {"name": "AndorrA", "code": "AD"}, {"name": "Angola", "code": "AO"}, {"name": "Anguilla", "code": "AI"}, {"name": "Antarctica", "code": "AQ"}, {"name": "Antigua and Barbuda", "code": "AG"}, {"name": "Argentina", "code": "AR"}, {"name": "Armenia", "code": "AM"}]; var c = countries.length / 4; var result = []; for(var i = 0; i < countries.length; i+=c) { result.push(countries.slice(i, i+c)); } 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