Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa đối tượng trùng lặp khỏi mảng JavaScript

Viết hàm xóa đối tượng trùng lặp từ mảng (coi trùng nếu cùng số key, cùng key, cùng value).

Dùng Map lưu chuỗi JSON của object, gặp trùng thì bỏ qua.

Ví dụ

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);

Kết quả

Đầu ra console:

[ { timestamp: 564328370007, message: 'It will rain today' }, { timestamp: 164328302520, message: 'will it rain today' } ]