希望你能理解我的问题。 假设我有这个数组:
[[1, 0.3], [1, 0.5], [2, 0.6], [2, 0.7], [3, 0.8], [3, 0.9]]
我想要基于第一个值的新数组,如下所示:
[0.3, 0.5]
[0.6, 0.7]
[0.8, 0.9]
它们是三个数组,因为有三个数字1和2和3,如果数字多了,那么应该多出来一些数组。
非常感谢。
最佳答案
您可以创建一个新对象,其中键是索引号(每个当前数组值的第一个索引),值是相关数字(第二个索引)。
var arr = [[1, 0.3], [1, 0.5], [2, 0.6], [2, 0.7], [3, 0.8], [3, 0.9]];
var newObj = {};
arr.map(function(item){
if(newObj[item[0]])
newObj[item[0]].push(item[1]);
else
newObj[item[0]] = [item[1]];
});
console.log('New object: ' + JSON.stringify(newObj));
// if you insist on creating an array
var newArr = [];
var cnt = 0;
for(var item in newObj)
{
if(newObj.hasOwnProperty(item))
{
newArr[cnt] = newObj[item];
cnt++;
}
}
console.log('New array: ' + JSON.stringify(newArr));
关于javascript - 根据数组的第一个值拆分数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34194854/