×ðÁú¿­Ê±¹ÙÍøµÇ¼

jsÔõôȥµôÊý×éÖظ´µÄ¹¤¾ß

ÔõÑùÔÚ javascript ÖÐÈ¥³ýÊý×éÖеÄÖظ´¹¤¾ß£¿set Êý¾Ý½á¹¹£º½¨Éè set£¬Ê¹ÓÃÆä²»´æ´¢Öظ´ÖµµÄÌصã¡£reduce() ÒªÁ죺ʹÓÃÀÛ¼ÓÆ÷º¯ÊýÖð¸ö¼ì²éÔªËØ£¬½«²»Öظ´ÔªËØ·ÅÈëÀÛ¼ÓÆ÷¡£filter() ºÍ indexof() ÒªÁ죺¹ýÂËË÷ÒýÓëÊý×éÖеÚÒ»¸öË÷ÒýÏàͬµÄÔªËØ£¬È¥³ýÖظ´¡£lodash ¿â£ºÊ¹Óà uniqby ÒªÁ죬»ùÓÚÖ¸¶¨ÊôÐÔÈ¥³ýÖظ´¹¤¾ß¡£

ÔõÑùÔÚ JavaScript ÖÐÈ¥³ýÊý×éÖеÄÖظ´¹¤¾ß

JavaScript Êý×éÖаüÀ¨¹¤¾ßʱ£¬ÎÒÃÇÐèÒª¶Ô¹¤¾ß¾ÙÐÐÈ¥ÖزÙ×÷¡£ÈÃÎÒÃÇÒ»²½Ò»²½ÉîÈëÏàʶÔõÑùÔÚ JavaScript ÖÐʵÏÖ´ËÄ¿µÄ¡£

1. ʹÓà Set Êý¾Ý½á¹¹

Set Êý¾Ý½á¹¹ÔÚ JavaScript ÖÐÊÇÒ»¸öÄÚÖõŤ¾ß£¬Ëü²»»á´æ´¢Öظ´Öµ¡£ÎÒÃÇ¿ÉÒÔʹÓÃËüÍù¸´³ýÊý×éÖеÄÖظ´¹¤¾ß£º

const originalArray = [{ name: 'John' }, { name: 'Jane' }, { name: 'John' }, { name: 'Mary' }];

const uniqueObjects = [...new Set(originalArray)];

console.log(uniqueObjects);
// Êä³ö: [{ name: 'John' }, { name: 'Jane' }, { name: 'Mary' }]

µÇ¼ºó¸´ÖÆ

2. ʹÓà reduce() ÒªÁì

reduce() ÒªÁìÔÊÐíÎÒÃÇʹÓÃÒ»¸öÀÛ¼ÓÆ÷º¯Êý½«Êý×éÔªËغϲ¢ÎªÒ»¸ö¼òµ¥µÄÖµ¡£ÎÒÃÇ¿ÉÒÔʹÓÃËüÀ´¹¹½¨Ò»¸ö²»º¬Öظ´¹¤¾ßµÄÊý×飺

const uniqueObjects = originalArray.reduce((acc, curr) => {
  const found = acc.find(obj => obj.name === curr.name);
  if (!found) acc.push(curr);
  return acc;
}, []);

console.log(uniqueObjects);
// Êä³ö: [{ name: 'John' }, { name: 'Jane' }, { name: 'Mary' }]

µÇ¼ºó¸´ÖÆ

3. ʹÓà filter() ºÍ indexOf() ÒªÁì

filter() ÒªÁìÔÊÐíÎÒÃÇ»ùÓÚÒ»¸öÌõ¼þº¯Êý¹ýÂËÊý×éÔªËØ¡£indexOf() ÒªÁì·µ»Ø¸ø¶¨ÔªËØÔÚÊý×éÖеĵÚÒ»¸öË÷Òý£¬ÈôÊDz»±£´æÔò·µ»Ø -1¡£ÎÒÃÇ¿ÉÒÔʹÓÃËüÃÇÀ´ÊµÏÖ¹¤¾ßÈ¥ÖØ£º

const uniqueObjects = originalArray.filter((obj, i) => originalArray.indexOf(obj) === i);

console.log(uniqueObjects);
// Êä³ö: [{ name: 'John' }, { name: 'Jane' }, { name: 'Mary' }]

µÇ¼ºó¸´ÖÆ

4. ʹÓà Lodash

Lodash ÊÇÒ»¸ö¹¦Ð§Ç¿Ê¢µÄ JavaScript ÊÊÓóÌÐò¿â¡£ËüÌṩÁËÒ»¸ö½Ð uniqBy µÄÒªÁ죬¿ÉÒÔ»ùÓÚÒ»¸ö¸ø¶¨µÄÊôÐÔÍù¸´³ýÊý×éÖеÄÖظ´¹¤¾ß£º

import { uniqBy } from 'lodash';

const uniqueObjects = uniqBy(originalArray, 'name');

console.log(uniqueObjects);
// Êä³ö: [{ name: 'John' }, { name: 'Jane' }, { name: 'Mary' }]

µÇ¼ºó¸´ÖÆ

ÒÔÉϾÍÊÇjsÔõôȥµôÊý×éÖظ´µÄ¹¤¾ßµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±¹ÙÍøµÇ¼ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼ʵʱÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
ÍøÕ¾µØͼ