从对象数组中删除重复项JavaScript
我们需要编写一个函数从数组中删除重复对象并返回一个新的数组。如果两个对象的键数相同、键相同且每个键的值相同,则认为一个对象是另一个对象的重复。
让我们写出如下代码:
我们将使用一个映射以字符串形式存储不同的对象,一旦看到重复的键,我们就忽略它,否则将对象推入新数组中:
示例
const arr = [ { "timestamp": 564328370007, "message": "It will rain today" }, { "timestamp": 164328302520, "message": "will it rain today" }, { "timestamp": 564328370007, "message": "It will rain today" }, { "timestamp": 564328370007, "message": "It will rain today" } ]; const map = {}; const newArray = []; arr.forEach(el => { if(!map[JSON.stringify(el)]){ map[JSON.stringify(el)] = true; newArray.push(el); } }); console.log(newArray);
输出
控制台中的输出为:
[ { timestamp: 564328370007, message: 'It will rain today' }, { timestamp: 164328302520, message: 'will it rain today' } ]
广告