我得到了countries.json
,我按照规范将其分为四列显示。
我正在寻找一种解决方案,其中数组元素均匀分布到所有四个数组。
示例JSFIDDLE https://jsfiddle.net/5tkjLs7b/
如果我从json数据中删除一个国家/地区,我将最终获得6个数组。但预计只有4个阵列。
此外,数据应均匀分布。
示例:我获得了63个项目* 4个数组+ 3个项目* 1个数组已满 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);
答案 0 :(得分:2)
您可以使用for
循环和slice()
来获得所需的结果。
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)