簡體   English   中英

映射和過濾數組 JavaScript

[英]Map and filter an array JavaScript

我正在嘗試映射一個嵌套數組並返回字母數超過 6 的單詞,我已經被這個問題困住了一段時間,所以我想得到一些幫助

const array = [["hellow",'pastas'],["travel", "militarie"],["oranges","mint"]]

  const arrayOne = array.map(new => new).filter(arr =>arr.length > 6)

您可以先進行flat數組,然后filter掉長度大於6單詞

 const array = [['hellow','pastas'],['travel', 'militaries'],['oranges','mint']] const arrayOne = array.flat(1).filter(e=> e.length > 6 ) console.log(arrayOne)

我認為更好的是 filter() 方法。

array.filter(function (c) {
    return c.length < 6;
});

但首先使用 flat() 方法。

您可以使用下面的代碼。 此代碼使用.map().filter()來檢查長度是否大於 6,如果是,則將其添加到數組中。

 const array = [["hellow","pastas"],["travel", "militarie"],["oranges","mint"]]; const arrayOne = array.map(e1 => e1.filter(e2 => e2.length > 6)).flat(); console.log(arrayOne);

有很多方法可以做到。

您可以使用flatMapfilter

 const array = [['hellow','pastas'],['travel', 'militarie'],['oranges','mint']]; const result = array.flatMap(x => x.filter(y => y.length > 6)); console.log(result);

另一種方法是使用reducefilter

 const array = [['hellow','pastas'],['travel', 'militarie'],['oranges','mint']]; const result = array.reduce((acc, x) => [...acc, ...x.filter(y => y.length > 6)], []); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM