简体   繁体   中英

Call forEach from anonymous function and store the result to variable

I need to get an array as input and store the result to be used, without creating other functions because I have no access. So the code must be what result can get.

let array = [[1,2,3,4,5,10],[1,2,3,4,5,20]];
let result = array
    .forEach(
        function(el){
            if(el[5] == 10)
            {
                return(el); //must store to variable, but this doesn't work
            }
        }
    )

I know I'm missing the point but can't figure it out. How can I make this work?

Since you need only some especific elements, you need a make a filter on the array

let array = [[1,2,3,4,5,10],[1,2,3,4,5,20]];
let result = array.filter((el) => el[5] == 10)

Use filter() .

let result = array.filter(el => el[5] === 10);

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