js 數組 find,some,filter,reduce區別詳解
區分清楚Array中filter、find、some、reduce這幾個方法的區別,根據它們的使用場景更好的應用在日常編碼中。
Array.findArray.find 返回一個對象(第一個滿足條件的對象)后停止遍歷
const arrTest = [ { id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'b' }, { id: 4, name: 'c' }]// 過濾條件function getName(val) { return arrTest => arrTest.name === val}
// 如果我們是想找到第一個滿足條件的數據,應該使用`Array.find`console.log(arrTest.find(getName('b')))// { id: 2, name: 'b' }Array.some
Array.some 返回是否滿足條件的布爾值
const arrTest = [ { id: 1, name: 'a', status: 'loading' }, { id: 2, name: 'b', status: 'loading' }, { id: 3, name: 'b', status: 'success' }]// 過濾條件function getStatus(val) { return arrTest => arrTest.status === val}
// 如果我們需要查找一個數組中是否存在某個數據的時候,使用Array.some直接拿到結果console.log(arrTest.some(getStatus('success')))// trueArray.filter
Array.filter 遍歷整個Array返回一個數組(包含所有滿足條件的對象)
const arrTest = [ { id: 1, name: 'a', status: 'loading' }, { id: 2, name: 'b', status: 'loading' }, { id: 3, name: 'b', status: 'success' }]// 過濾條件function getStatus(val) { return arrTest => arrTest.status === val} // 如果我們是需要過濾出一個數組中所有滿足條件的數據,應該使用Array.filterconsole.log(arrTest.filter(getStatus('loading')))// [// { id: 1, name: 'a', status: 'loading' },// { id: 2, name: 'b', status: 'loading' }// ]Array.reduce
Array.reduce 為數組的歸并方法,使用場景很多,比如求和、求乘積,計次,去重,多維轉一維,屬性求和等...本節示例主要實現Array.reduce對一組數據進行條件過濾后,返回一個新的數組
const arrTest = [ { id: 1, status: 'loading' }, { id: 2, status: 'loading' }, { id: 3, status: 'success' }]console.log( arrTest.reduce((acc, character) => {return character.status === 'loading' ? acc.concat( Object.assign({}, character, { color: 'info' }) ) : acc }, []))// [// { id: 1, status: 'loading', color: 'info' },// { id: 2, status: 'loading', color: 'info' }// ]
與Array.filter返回的數組的不同,filter返回的是原數組中符合條件的對象集合,filter與 Array.map 結合也可以實現上面的結果,為什么使用reduce更好呢?
// Array.map 和 Array.filter 組合console.log( arrTest.filter(character => character.status === 'loading').map(character => Object.assign({}, character, { color: 'info' })))// [// { id: 1, status: 'loading', color: 'info' },// { id: 2, status: 'loading', color: 'info' }// ]
結論:同時使用 Array.filter 和 Array.map 的時候,對整個數組循環了 2 遍。第一次是過濾返回一個新的數組,第二次通過 map 又構造一個新的數組。使用了兩個數組方法,每一個方法都有各自的回調函數,而且 filter 返回的數組以后再也不會用到。使用 Array.reduce 同樣的結果,代碼更優雅。
到此這篇關于js 數組 find,some,filter,reduce區別詳解的文章就介紹到這了,更多相關js 數組 find,some,filter,reduce內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
