How can I only keep items of an array that match a certain condition?

前端 未结 3 1820
轻奢々
轻奢々 2020-11-27 21:25

I have an array, and I want to filter it to only include items which match a certain condition. Can this be done in JavaScript?

Some examples:

[1, 2,         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 21:44

    A more concise answer following the one from @Scimonster, using ES6 syntax, would be:

     // even numbers
    const even = [1, 2, 3, 4, 5, 6, 7, 8].filter(n => n%2 == 0);
    // words with 2 or fewer letters
    const words = ["This", "is", "an", "array", "with", "several", "strings", "making", "up", "a", "sentence."].filter(el => el.length <= 2);
    // truable elements
    const trues = [true, false, 4, 0, "abc", "", "0"].filter(v => v);
    
    console.log(even);
    console.log(words);
    console.log(trues);

提交回复
热议问题