2016-09-23 51 views
-2

我在javascript數組中有一大組對象。我需要找到具有相同名稱的所有重複對象。返回重複的對象,並在javascript中的位置

例如

values = [ 
    { name: 'Name1', index:0 }, 
    { name: 'Name2', index:1 }, 
    { name: 'Name1', index:2 }, 
    { name: 'Name2', index:3 }, 
    { name: 'Name1', index:4 }, 
] 

我想到的是有兩個對象

values = [ 
    { name: 'Name1', index:2 }, 
    { name: 'Name2', index:3 }, 
    { name: 'Name1', index:4 } 
] 

,因爲這些都是重複一個陣列。

+0

檢查: HTTP ://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array and that: http://stackoverflow.com/questions/9229645/remove-duplicates - 從-JavaScript的一個rray – 2016-09-23 14:33:08

回答

0

ES6的新增功能在這裏非常有趣,例如Set類。此代碼不會修改您的初始對象,但它很容易適應。

function unique(values) { 
    const knownNames = new Set(); 
    const result = []; 

    for (const value of values) { 
    if (!knownNames.has(value.name)) { 
     knownNames.add(value.name); 
     result.push(value); 
    } 
    } 

    return result; 
} 
0

這可能不是最有效的方法,你或許應該使用設置,如果你不需要擔心IE9

values = [ 
 
    { name: 'Name1', index:0 }, 
 
    { name: 'Name2', index:1 }, 
 
    { name: 'Name1', index:2 }, 
 
    { name: 'Name2', index:3 }, 
 
    { name: 'Name1', index:4 }, 
 
] 
 

 
// check an array for an object with a matching name property 
 
// `some` will return early so you don't need to process the whole array 
 
// if a match is found 
 
const contains = (name, arr) => arr.some(item => item.name === name) 
 

 
// reduce the array to keep the value contained 
 
const output = values.reduce((acc, value) => { 
 
    if (!contains(value.name, acc)) { 
 
    return acc.concat(value) 
 
    } 
 
    return acc 
 
}, []) 
 

 
console.log('first unique', output)