美文网首页
JS数组对象去重

JS数组对象去重

作者: 海山城 | 来源:发表于2019-05-24 17:03 被阅读0次
待去重数组
let array = [{
  code: '1111',
  value: '海山城1111'
}, {
  code: '2222',
  value: '海山城2222'
}, {
  code: '3333',
  value: '海山城3333'
},{
  code: '4444',
  value: '海山城4444'
},{
  code: '1111',
  value: '海山城1111'
},{
  code: '4444',
  value: '海山城4444'
}];
  • 方法一:for循环
/**
 * @description: 数组对象去重
 * @param array: 待去重数组
 * @param key: 数组的对象以此key去重
 * @return: 去重后的数组
 */
removeDuplication = (array, key) => {
  let result = []
  let keyArray = []
  for (let i in array){  
    if (!keyArray.includes(array[i][key])) {
      result.push(array[i])
      keyArray.push(array[i][key])
    }
  }
  return result
};

let result = removeDuplication (array, 'code')
console.log("result", result)
  • 方法二:reduce
/**
 * @description: 数组对象去重
 * @param array: 待去重数组
 * @param key: 数组的对象以此key去重
 * @return: 去重后的数组
 */
removeDuplication = (array, key) => {
  let keyMap = {};
  return array.reduce(function(accumulator, currentValue) {
    if (!keyMap[currentValue[key]]) {
      accumulator.push(currentValue);
      keyMap[currentValue[key]] = true;
    }
    return accumulator;
  }, []);
};
let result = removeDuplication (array, 'code')
console.log("result", result)

相关文章

网友评论

      本文标题:JS数组对象去重

      本文链接:https://www.haomeiwen.com/subject/jaghzqtx.html