在 JavaScript 中,數(shù)組去重,對(duì)象去重,可以使用多種方法來去除數(shù)組或?qū)ο笾械闹貜?fù)項(xiàng)。以下是其中的一些方法:
去除數(shù)組中的重復(fù)項(xiàng)
方法一:使用 Set
使用 Set 是去除數(shù)組中重復(fù)項(xiàng)的最簡(jiǎn)單和最快的方法。Set 對(duì)象是一組不重復(fù)的值的集合,可以接受一個(gè)數(shù)組(或者具有可迭代屬性的其他對(duì)象)作為參數(shù),并返回一個(gè)包含不重復(fù)元素的新數(shù)組。例如:
javascriptCopy code
const arr = [1, 2, 3, 3, 4, 5, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
方法二:使用 filter 和 indexOf
使用 filter 和 indexOf 方法可以從數(shù)組中刪除重復(fù)項(xiàng)。例如:
javascriptCopy code
const arr = [1, 2, 3, 3, 4, 5, 5];
const uniqueArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(uniqueArr); // [1, 2, 3, 4, 5]
方法三:使用 reduce 和 includes
使用 reduce 和 includes 方法可以從數(shù)組中刪除重復(fù)項(xiàng)。例如:
javascriptCopy code
const arr = [1, 2, 3, 3, 4, 5, 5];
const uniqueArr = arr.reduce((prev, cur) => {
if (!prev.includes(cur)) {
prev.push(cur);
}
return prev;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]
去除對(duì)象中的重復(fù)項(xiàng)
方法一:使用 for…in 和 hasOwnProperty
使用 for…in 循環(huán)遍歷對(duì)象的屬性,并使用 hasOwnProperty 方法檢查屬性是否是對(duì)象自身的屬性。例如:
javascriptCopy code
const obj = {
a: 1,
b: 2,
c: 3,
d: 3,
e: 4,
f: 4
};
const uniqueObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
uniqueObj[obj[key]] = key;
}
}
console.log(uniqueObj); // { '1': 'a', '2': 'b', '3': 'c', '4': 'e' }
方法二:使用 Object.keys 和 reduce
使用 Object.keys 方法獲取對(duì)象的所有屬性,然后使用 reduce 方法來去除重復(fù)項(xiàng)。例如:文章來源:http://www.zghlxwxcb.cn/news/detail-596600.html
javascriptCopy code
const obj = {
a: 1,
b: 2,
c: 3,
d: 3,
e: 4,
f: 4
};
const uniqueObj = Object.keys(obj).reduce((prev, key) => {
const value = obj[key];
if (!prev.hasOwnProperty(value)) {
prev[value] = key;
}
return prev;
}, {});
console.log(uniqueObj); // { '1': 'a', '2': 'b', '3': 'c', '4': 'e' }
以上是去除數(shù)組或?qū)ο笾械闹貜?fù)項(xiàng)的幾種方法。選擇哪種方法取決于個(gè)人喜好和具體情況。文章來源地址http://www.zghlxwxcb.cn/news/detail-596600.html
到了這里,關(guān)于js實(shí)用篇-去除數(shù)組或者對(duì)象里重復(fù)選項(xiàng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!