admin管理员组文章数量:1400420
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
2 Answers
Reset to default 2You 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);
本文标签: Skip element in array using map in javascriptStack Overflow
版权声明:本文标题:Skip element in array using map in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744255652a2597469.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论