JavaScript数组去重

/// <summary>
/// 数组去重
/// </summary>
/// <param name="fieldName">去重的字段名</param> 
Array.prototype.distinct = function (fieldName) {
    var arr = this;
    var uniqueArr = [];
    var includedKey = {};
    for (var i = 0; i < arr.length; i++) {
        var value = arr[i][fieldName];
        if (includedKey[value]) continue;
        uniqueArr.push(arr[i]);
        includedKey[value] = 1;
    }
    return uniqueArr;
}
// 测试
var test = [{ id: '1' }, { id: '2' }, { id: '2' }, { id: '1' }, { id: '3' }];
test = test.distinct('id');
alert(JSON.stringify(test));

 

posted @ 2016-12-14 14:34  天碼行空  阅读(359)  评论(0编辑  收藏  举报