Home > front end >  Break map() function in React JS based on condition
Break map() function in React JS based on condition

Time:06-24

Requirement: Basically I have an array of employee object in React JS, say empList. This empList contains primitive fields & again an inner array of another "address" objects, say addressList. I want to fetch data for all employees if they belong to city "ABC". They can have multiple address in city "ABC", but they should be fetched only once & pushed into finalList only once.

Problem : I am able to filter the employees having address in city "ABC" but in case, they have multiple address in city "ABC", then they are added to the finalList multiple times. So, I want to check for all addresses for an employee & in case, any one is found in city "ABC", I want to add it to finalList, break this inner map() function & go to outer map() to check for next employee.

Below is my code snippet.

var finalList =[];
empList.map(function(employee) {
           
            var valid = employee.addressList.map(function(address) {
                if (address.city.startsWith("ABC")) {
                    finalList.push(employee);
                    //Employee pushed to validList once, so now break from inner map() function & goto second line/execute on next employee object 
                  
                }
            });     //.slice(0,1); Slice doesn't work here since I want the condition to be true first, then break it.

CodePudding user response:

You can use the some which tests whether at least one element in the array passes the test condition.

Read about some here.

var finalList =  empList.filter(e => e.addressList.some(a => a.city.startsWith("ABC")));

Also I've updated your logic to use filter (instead of map) which creates a new array with all elements that pass the provided condition.

You can read about filter at here.

  • Related