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?

1

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.