daily-interview / fe-interview

:smiley: 每日一道经典前端面试题,一起共同成长。
https://blog.csdn.net/u010494753
MIT License
172 stars 22 forks source link

js实现普通数组去重&json数组去重 #65

Open artdong opened 3 years ago

artdong commented 3 years ago

js实现普通数组去重&json数组去重

artdong commented 3 years ago

普通数组去重(https://github.com/daily-interview/fe-interview/issues/24)

json数组去重

方法一 使用reduce及key的唯一性

/**
 * json数组去重
 * @param  {Array} jsonArray去重之前的数组
 * @param  {String} fieldName  需要去重的字段值
 * @return {Array}        去重之后的数组
 */
function uniqueJsonArrayByFieldName(jsonArray, fieldName) {
    let hash = {}; 
    let uniqueArr = [];
    if(!(Object.prototype.toString.call(jsonArray).toLowerCase() == "[object array]")) return []; // 不是数组
    uniqueArr = jsonArray.reduce((preVal, curVal) => {
        if(!(Object.prototype.toString.call(curVal).toLowerCase() == "[object object]")) return []; // 不是json对象
        if(!curVal.hasOwnProperty(fieldName)) return []; // 没有fieldName属性
        hash[curVal[fieldName]] ? '' : hash[curVal[fieldName]] = true && preVal.push(curVal); 
        return preVal 
    }, []);
    hash = null;
    return uniqueArr;
}

方法二 循环

/**
 * json数组去重
 * @param  {Array} jsonArray去重之前的数组
 * @param  {String} fieldName  需要去重的字段值
 * @return {Array}        去重之后的数组
 */
function uniqueJsonArrayByFieldName(jsonArray, fieldName) {
    let dest = [];
    if(!(Object.prototype.toString.call(jsonArray).toLowerCase() == "[object array]")) return []; // 不是数组
    for (let i = 0; i < jsonArray.length; i++) {
        let item = jsonArray[i];
        if(!(Object.prototype.toString.call(item ).toLowerCase() == "[object object]")) return []; // 不是json对象
    if(!item.hasOwnProperty(fieldName)) return []; // 没有fieldName属性
        if (i == 0) {
            dest.push(item);
        } else {
            let filterData = dest.filter(function (f_item) {
                return f_item[fieldName] == item[fieldName];
            });
            if (filterData.length == 0) {
                dest.push(item);
            }
        }
    }
    return dest;
}