2017-07-02 98 views
0

我想寫一個函數接受一個對象數組,只選擇對象中的一個特定的鍵,並只返回該數組的唯一值到一個新的「過濾」數組。我試圖使用Array.filter,並不斷收到我的過濾數組未定義的錯誤。我哪裏錯了?不能只過濾一個數組的唯一值

const findUniques = function(arr) { 


let rawArray = arr.map(res => res.id); 

let filtered = rawArray.filter((id) => { 
    return filtered.indexOf(id) === -1; 
}); 
console.log(filtered) 


}; 

這裏是我過濾的數組模擬。

1630489261, 1630489261, 1630489261, 1630489313, 1630489313, 1630489261, 1630489313, 1707502836, 1590711681, 1588295455, 1630489313, 1707502836, 1588295455, 1707502836, 1590711681, 1707502836, 1707502836, 1707502836, 1707502836, 1707502836, 1588295455, 1588295455 

如果我將過濾器設置爲全局變量,它會被填充但它不會被過濾。 I.E.過濾正在填充rawArray中的所有內容。

+1

,請向我們提供您的響應(RES VAR)的至少模擬 –

+0

@YuriRamos我不好。更新 –

+1

我認爲你的代碼會導致一些初始化錯誤,因爲例如你在初始化之前使用「過濾」變量。 – jrook

回答

1

使用Array#filter

rawArray = [1, 2, 3, 2, 3, 1, 4]; 
 

 
filtered = rawArray.filter((e, i) => rawArray.indexOf(e) === i); 
 
    
 
console.log(filtered);

使用Array#reduce

let rawArray = [1, 2, 3, 2, 3, 1, 4], 
 
filtered = rawArray.reduce(function (acc, item) { 
 
    if (!acc.includes(item)){ 
 
     acc.push(item); 
 
    } 
 
    return acc; 
 
}, []); 
 
console.log(filtered);

+0

您能否解釋Array.filter選項的隱式返回如何工作?如何rawArray.indexOf(e)=== i)返回true或false –

+0

@什麼的發佈'rawArray.indexOf(e)===我'檢查這個項目之前是否添加,這個小提琴將有助於瞭解發生了什麼裏面的過濾器(在我們的例子中是過濾器)https://jsfiddle.net/ee5s067q/ –

+0

@Somethingismissing過濾器像循環一樣工作'e'表示原始數組(rawArray)中的當前元素。 'i'表示新數組的當前索引(已過濾) –

0
const values = [1630489261, 1630489261, 1630489261, 1630489313, 1630489313, 1630489261, 1630489313, 1707502836, 1590711681, 1588295455, 1630489313, 1707502836, 1588295455, 1707502836, 1590711681, 1707502836, 1707502836, 1707502836, 1707502836, 1707502836, 1588295455, 1588295455]; 


function unique(array) { 
    return array.reduce((a,b) => { 
    let isIn = a.find(element => { 
     return element === b; 
    }); 
    if(!isIn){ 
     a.push(b); 
    } 
    return a; 
    },[]); 
} 

let ret = unique(values); 

console.log(ret); 

https://jsfiddle.net/26bwknzf/4/

+0

您不需要使用需要函數的'find'。你可以簡單地使用'indexOf'或'includes'。 –