How to make a return for a function that has .map() but the return will be inside .map()

Tell us what’s happening:
I wonder how to make a return for dropElements1 function that has map() inside?
or
How to terminate map execution based on a condition and at the same time make a return for dropElements1 function?

Your code so far

function dropElements1(arr, func) {
  arr.map(element => {
    (func(element))? arr.slice(arr.indexOf(element)) : [];
  })
}

function dropElements(arr, func) {
for(let i =0 ; i< arr.length -1; i++){
  if(func(arr[i])){
    return arr.slice(arr.indexOf(arr[i]));
  }
}
return [];
}

dropElements([1, 2, 3], function(n) {return n < 3; });

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Drop it

Link to the challenge:

The map method is a transform method. It returns the same length array as it is invoked on. It is used to transform the values inside the array, not alter the array length.

I think you will find most of the array methods that are like map to not be very useful for this challenge as they will visit all the elements of the array and are not meant to be broken out of.

Yeah if you need to be able to break out of a loop in Javascript, you usually want to use the syntax above.

1 Like