简体   繁体   中英

How could I select specific elements from a array?

Using this characters array, print to the console every character which name begins with 'M'. Don't use any kind of loop, yet. Just print to console each name separately.

        var filmCharacters =[

        ['Vito', 'Michael', 'Sonny', 'Freddo'],

        ['Mia', 'Vincent', 'Jules', 'Butch'], 

        ['Bella', 'Edward', 'Jacob', 'Carlisle'],

        ['James', 'M', 'Moneypenny', 'Felix']

];

You can achieve this by using the reduce on the outer array and then filtering the inner array.

After filtering you can join them back together with the current values

> filmCharacters.reduce((acc, curr) => [...acc, ...curr.filter(x => x.startsWith('M'))], [])
[ 'Michael', 'Mia', 'M', 'Moneypenny' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM