数组去重
1 var arr = [{id:1},{id:3},{id:1},{id:4}]; 2 var newArr = arr.filter((value, index, array) => { 3 console.log(value,index,array.map((item) => {return item.id;}).indexOf(value.id)); 4 return array.map((item) => {return item.id;}).indexOf(value.id) == index 5 }); 6 console.log(newArr)
输出:
1 var arr = [1, 2, 2, 3, 3, 3, 4, 5]; 2 var newArr = arr.filter((value, index, array) => array.indexOf(value) === index); 3 console.log(newArr)
输出:
1 /* 2 * JSON数组去重 3 * @param: [array] json Array 4 * @param: [string] 唯一的key名,根据此键名进行去重 5 */ 6 export function uniqueArray(array, key) { 7 var result = [array[0]]; 8 for (var i = 1; i < array.length; i++) { 9 var item = array[i]; 10 var repeat = false; 11 for (var j = 0; j < result.length; j++) { 12 if (item[key] == result[j][key]) { 13 repeat = true; 14 break; 15 } 16 } 17 if (!repeat) { 18 result.push(item); 19 } 20 } 21 return result 22 }
代码截图展示: