【前端】JS去重

 

/*
* JSON数组去重
* @param: [array] json Array
* @param: [string] 唯一的key名,根据此键名进行去重
*/
export const uniqueArray = (array, key) => {
    var result = [array[0]];
    for (var i = 1; i < array.length; i++) {
        var item = array[i];
        var repeat = false;
        for (var j = 0; j < result.length; j++) {
            if (item[key] == result[j][key]) {
                repeat = true;
                break;
            }
        }
        if (!repeat) {
            result.push(item);
        }
    }
    return result;
}


/*
* 数组去重
*/
const oldArr = [1,1,3,2,5,3,6,6,6,7,3]
const newArr = [...new Set(oldArr)] 
console.log(newArr) // [1, 3, 2, 5, 6, 7]

 

posted @ 2022-11-21 22:36  淡怀  阅读(27)  评论(0编辑  收藏  举报