2014-10-30 60 views
0

我有一个包含行信息的对象数组。我正在尝试过滤这些信息,以便只有一次包含每个行值的新数组。所以下面的对象会输出这样的数组:['1', '2', '3']将对象数组过滤到新数组中

这是我的代码。我想在地图功能,但不知道这是正确的做法:

var myArray = [ 
 
    { 
 
     "row": 1, 
 
     "headline": "First Object" 
 
    }, 
 
    { 
 
     "row": 1, 
 
     "headline": "Second Object" 
 
    }, 
 
    { 
 
     "row": 2, 
 
     "headline": "Third Object" 
 
    }, 
 
    { 
 
     "row": 2, 
 
     "headline": "Fourth Object" 
 
    }, 
 
    { 
 
     "row": 3, 
 
     "headline": "Fifth Object" 
 
    } 
 
]; 
 
    
 
    var rows = myArray.map(function(row) { 
 
     console.log(row) 
 
    });

回答

1

这样做很可能是写所有属性的一个对象的最简单方法,然后把它们写回数组:

var o = {}, 
    uniqueArray = []; 

myArray.forEach(function (d) { 
    o[d.row] = true; // stores the key equal to d.row in the object 
}); 
for (var k in o) { // loop through all the keys in o 
    if (o.hasOwnProperty(k)) // if the object o has that key 
     uniqueArray.push(k); // push it to the array 
} 
console.log(uniqueArray); 
// ["1", "2", "3"]; 
+0

谢谢!这正是我所期待的。 – Mdd 2014-10-30 02:14:33

1

把所有的行值在数组中......

var arrayAll = []; 
for (var i = 0; i < myArray.length; i++) { 
    arrayAll.push(myArray[i].row) 
} 

然后删除重复

var uniqueNames = []; 
$.each(arrayAll, function (i, el) { 
    if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el); 
}); 

console.log(uniqueNames); 

看到这个职位的其他选项删除重复,如果你需要一个非JQuery的选项。 Remove Duplicates from JavaScript Array

+0

你绝对不需要jQuery来解决这个问题。 – royhowie 2014-10-30 02:09:41

+0

我知道,您是否看到我添加的链接? – Urielzen 2014-10-30 02:11:45

+0

@Urielzen谢谢!这个链接真的很好! – Mdd 2014-10-30 02:16:27

1

对于更易读的方式,则选择答案,我会去的:

var distinct = function(rows){ 
    var mappedValues = rows.map(function(single){ 
     return single.row; 
    }); 
    return mappedValues.filter(function(item,pos){ 
     return mappedValues.indexOf(item) === pos; 
    }); 
} 

distinct(myArray); 

只是我的2美分。

+1

唯一的问题是这是'O(n^2)'。大型数据集将非常慢。 – royhowie 2014-10-30 06:17:28

+0

@royhowie因为我和你有同样的想法,所以我做了一个jsperf来测试它作为本地函数,或者有时非常好的优化。即使使用更大的数据集,我的速度也会提高3倍。 http://jsperf.com/filter123 – 2014-10-30 10:38:24

+0

@royhowie对不起,我必须原谅自己,我做了我的测试用例大阵复制数组没有考虑改变数字。您的解决方案确实是大阵列中更好的解决方案。 – 2014-10-30 11:07:44