jsÖÐÊý×éÈ¥ÖصÄÒªÁì
ÔÚ javascript ÖУ¬´ÓÊý×éÖÐɾ³ýÖظ´ÏîµÄÒªÁì°üÀ¨£ºÊ¹Óà set()¡¢Ê¹Óà filter() ¼ì²éË÷Òý¡¢Ê¹Óà foreach() ¼ì²éË÷Òý¡¢Ê¹Óà reduce() ÀÛ»ý²»Öظ´Öµ¡£
ÔõÑùÔÚ JavaScript ÖдÓÊý×éÖÐɾ³ýÖظ´Ïî
ÔÚ JavaScript ÖУ¬´ÓÊý×éÖÐɾ³ýÖظ´ÏîÓÐÒÔϼ¸ÖÖ³£¼ûÒªÁ죺
1. ʹÓà Set()
Set() ÊÇÒ»¸öÄÚÖÃÜöÝÍ£¬Ëü¿ÉÒÔ×Ô¶¯É¾³ýÖظ´Öµ¡£Ê¹Óà Set() ´ÓÊý×éÖÐɾ³ýÖظ´ÏîµÄ°ì·¨ÈçÏ£º
const arr = ['a', 'b', 'c', 'a', 'd']; const uniqueArr = [...new Set(arr)]; // [ 'a', 'b', 'c', 'd' ]
µÇ¼ºó¸´ÖÆ
2. ʹÓà filter()
filter() ÒªÁì¿ÉÒÔ¹ýÂËÊý×éÖеÄÔªËØ£¬²¢·µ»ØÒ»¸öÐÂÊý×飬ÆäÖÐÖ»°üÀ¨Öª×ã¸ø¶¨Ìõ¼þµÄÔªËØ¡£ÒªÊ¹Óà filter() ´ÓÊý×éÖÐɾ³ýÖظ´Ï¿ÉÒÔÈçÏÂʹÓãº
const arr = ['a', 'b', 'c', 'a', 'd']; const uniqueArr = arr.filter((item, index, self) => self.indexOf(item) === index); // [ 'a', 'b', 'c', 'd' ]
µÇ¼ºó¸´ÖÆ
3. ʹÓà forEach() ºÍ index
¿ÉÒÔʹÓà forEach() ÒªÁì±éÀúÊý×éÖеÄÿ¸öÔªËØ£¬²¢Ê¹ÓÃË÷ÒýÀ´¼ì²éÊÇ·ñÒÑ°üÀ¨¸ÃÔªËØ¡£ÈôÊÇÒÑ°üÀ¨£¬Ôò½«Æä´ÓÊý×éÖÐɾ³ý¡£
const arr = ['a', 'b', 'c', 'a', 'd']; arr.forEach((item, index, self) => { if (self.indexOf(item) !== index) { arr.splice(index, 1); } }); // [ 'a', 'b', 'c', 'd' ]
µÇ¼ºó¸´ÖÆ
4. ʹÓà reduce()
reduce() ÒªÁì¿ÉÒÔ½«Êý×éÖеÄÔªËØÀÛ»ýΪһ¸ö×îÖÕÖµ¡£ÒªÊ¹Óà reduce() ´ÓÊý×éÖÐɾ³ýÖظ´Ï¿ÉÒÔÈçÏÂʹÓãº
const arr = ['a', 'b', 'c', 'a', 'd']; const uniqueArr = arr.reduce((acc, item) => { if (!acc.includes(item)) { acc.push(item); } return acc; }, []); // [ 'a', 'b', 'c', 'd' ]
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÖÐÊý×éÈ¥ÖصÄÒªÁìµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡