remove the repeat element in an array of Objects
/**
* remove the repeat element in an array of Objects
*
* @param {Array} originalArray - original Array
* @param {String} [prop=undefined] - optional, if this field has set and vaild,
* then the function will remove repeat by the appointed key, else remove
* repeat by all keys
* @returns {Array} - new Array
*/
function removeRepeat(originalArray, prop) {
// type checker
if (originalArray && (originalArray instanceof Array)) {
if (originalArray.length <= 1) {
return originalArray;
}
let newArray = [];
// type checker
if (prop && (typeof prop === 'string')) {
// check if the prop is vaild
if (Object.keys(originalArray[0])
.includes(prop)) {
let repeatKiller = {};
// use the feature of Object[no repeat key] to remove repeat array element
originalArray.forEach(function(el) {
repeatKiller[el[prop]] = el;
});
// put the values of repeatKiller Object to the newArray
Object.keys(repeatKiller)
.forEach(function(el) {
newArray.push(repeatKiller[el]);
});
} else {
newArray = [...new Set(originalArray.map(JSON.stringify))].map(JSON.parse)
}
} else {
newArray = [...new Set(originalArray.map(JSON.stringify))].map(JSON.parse)
}
// return the newArray
return newArray;
}
}
// array of Objects
let shops = [{
shopName: "shop 1",
id: 1000
}, {
shopName: "shop 21",
id: 1001
}, {
shopName: "shop 21",
id: 1002
}, {
shopName: "shop 1",
id: 1000
}, {
shopName: "shop 41",
id: 1004
}, {
shopName: "shop 1",
id: 1005
}, {
shopName: "shop 61",
id: 1006
}];
// tests
console.log(removeRepeat(shops.slice(0, 1))) // array(length<=1)
console.log('\n')
console.log(removeRepeat(shops)) // array(length>1)
console.log('\n')
console.log(removeRepeat(shops, 'shopName')) // has vaild prop
console.log('\n')
console.log(removeRepeat(shops, 'invalidKey')) // invalid prop
console.log('\n')
console.log(removeRepeat(shops, ['shopName'])) // invalid prop
console.log('\n')
console.log(removeRepeat(shops[0])) // invaild array