简体   繁体   中英

Can I rewrite this double loop with condition better (shorter) using array methods in Javascript

Can I rewrite this double loop with a condition and a method call inside in a better way (shorter) using array methods in Javascript?

listA.forEach(a => {
    listB.forEach(b => {
        if (a.name === b.name) {
            a.doSomething(b);
        }
    });
});

Not sure it's better, but you can do something like this:

listA
    .map(a => listB.map(b => ({ a, b }))) // Create Pairs of { a, b } 
    .reduce((r, a) => a.concat(r)) // flatten { a, b }[][] to { a, b }[]
    .filter(o => o.a == o.b) // filter the list 
    .forEach(o => o.a.doSomething(o.b)); // call the function

You could change your if statement to:

a.name === b.name && a.doSomething(b);

Idk if that's the kind of better/shorter you are looking for. It uses short-circuit evaluation .

It's no where shorter but maybe more readable and it's more a stream-way of doing javascript without having all those nested loops:

listA
.filter(a => listB.map(b => b.name).includes(a.name))
.forEach(a => {
    console.log(a) // do your stuff here :)
})

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