2

is it possible to skip values while using the map method in javascript?

so for example

<!DOCTYPE html>
<html>
<body>


<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var numbers = [4, 9, 16, 25];

function myFunction() {
    x = document.getElementById("demo")
    x.innerHTML = numbers.map(Math.sqrt);
}
</script>

</body>
</html>

this code is going to output 2,3,4,5

but can you make it output 2,4 so it checks the first value in the array then skips the second until the end

or

3,5 so it skips the first value in the array then checks the second value.

is this possible using the map method? or do I have to use a for loop?

ylimes
  • 77
  • 1
  • 3
  • 10
  • 1
    Possible duplicate of [How to skip over an element in .map()?](https://stackoverflow.com/questions/24806772/how-to-skip-over-an-element-in-map) – ssc-hrep3 Nov 06 '18 at 18:43

2 Answers2

2

You can use .filter() on the mapped array:

let numbers = [4, 9, 16, 25];

let output1 = numbers.map(Math.sqrt).filter((_, i) => (i % 2 == 0));
let output2 = numbers.map(Math.sqrt).filter((_, i) => (i % 2 != 0));

console.log(output1);
console.log(output2);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
2

Is not possible using the function map because this function creates a new array with the same length of the source array.

An alternative is using the function reduce.

var numbers = [4, 9, 16, 25];
var result = numbers.reduce((a, n, i) => {
  if (n % 2 === 0) a.push(Math.sqrt(n));
  return a;
}, []);

console.log(result);
Ele
  • 33,468
  • 7
  • 37
  • 75
  • I like this one, especially when you are working with types. A scenario for which I used it was combining different arrays that actually all resembled the same data. Combining them meant having to do an Array.find() in the map, which resulted to having the possibility of encountering 'undefined'. Using reduce like this made it easy to enforce a single return type and skip all the theoretically possible undefineds (which were actually never there). – Khamaseen Sep 02 '22 at 08:21