[英]How to dynamically create an array using JavaScript?
我有這種形式的數組
['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297','203,548', '204,548', '204,548' ]
需求輸出:
0:['203,448', '204,448', '230,448','24,448', ]
1: [ '204,297', '205,297', '231,297', '24,297']
2: ['203,548', '204,548', '204,548']
我想sepreate 2 featur的即203,448和204,297基極上的元素
您可以將哈希表用於字符串的第二部分,並在數組中收集相同的項。
var data = ['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297', '203,548', '204,548', '204,548'], hash = Object.create(null), result = data.reduce(function (r, a) { var key = a.split(',')[1]; if (!hash[key]) { hash[key] = []; r.push(hash[key]); } hash[key].push(a); return r; }, []); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
對於僅放置第一部分,可以使用拆分數組
var data = ['203,448', '204,297', '204,448', '205,297', '230,448', '231,297', '24,448', '24,297', '203,548', '204,548', '204,548'], hash = Object.create(null), result = data.reduce(function (r, a) { var s = a.split(','); if (!hash[s[1]]) { hash[s[1]] = []; r.push(hash[s[1]]); } hash[s[1]].push(s[0]); return r; }, []); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.