最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Skip element in array using map in javascript - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question asked Nov 6, 2018 at 18:37 ylimesylimes 771 gold badge3 silver badges10 bronze badges 1
  • 1 Possible duplicate of How to skip over an element in .map()? – ssc-hrep3 Commented Nov 6, 2018 at 18:43
Add a ment  | 

2 Answers 2

Reset to default 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);

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

发布评论

评论列表(0)

  1. 暂无评论