admin管理员组文章数量:1356933
The code is to return the lowest index in an array when the value in the array is the same as the index. If there are no matches i should return -1. For example:
indexEqualsValue([-8,0,2,5])
output: 2 //array[2] == 2
indexEqualsValue([-1,0,3,6])
output: -1 //no matches
The code works when there are no matches or if the length of the array is zero, but not at other times. I think the problem is the first condition in my if statement. I don't necessarily want an answer, more tips on what I should check/rewrite.
Thanks!
function indexEqualsValue(a) {
return a.reduce((acc, currV, currI) => {
if (currI === currV) {
return currV;
}
return -1;
}, 0);
}
The code is to return the lowest index in an array when the value in the array is the same as the index. If there are no matches i should return -1. For example:
indexEqualsValue([-8,0,2,5])
output: 2 //array[2] == 2
indexEqualsValue([-1,0,3,6])
output: -1 //no matches
The code works when there are no matches or if the length of the array is zero, but not at other times. I think the problem is the first condition in my if statement. I don't necessarily want an answer, more tips on what I should check/rewrite.
Thanks!
function indexEqualsValue(a) {
return a.reduce((acc, currV, currI) => {
if (currI === currV) {
return currV;
}
return -1;
}, 0);
}
Share
Improve this question
edited Sep 5, 2018 at 10:33
shokha
3,1994 gold badges27 silver badges38 bronze badges
asked Aug 17, 2018 at 12:02
ValerieValerie
1111 silver badge8 bronze badges
3 Answers
Reset to default 9You could just find the index with Array#findIndex
.
const indexEqualsValue = array => array.findIndex((v, i) => v === i);
console.log(indexEqualsValue([-8, 0, 2, 5])); // 2
console.log(indexEqualsValue([-1, 0, 3, 6])); // -1
some
exits when it matches, so you can use it to quickly find what you need:
const indexEqualsValue = array => {
let match;
const didMatch = array.some((v, i) => {
match = i;
return v === i;
})
return didMatch ? match : -1;
}
console.log(indexEqualsValue([-8,0,2,5]))
console.log(indexEqualsValue([-8,0,2,5,0]))
console.log(indexEqualsValue([-1,0,3,6]))
nina-scholz's answer is better, the only advantage of using some
over findIndex
is that some
is supported in ie whereas it seems findIndex
is not.
for(i = 0,c=0;i < arr.length; i++ ) {
if(arr[i] == i) {
c = 1;
break;
}
}
if( c == 0 ) {
print(c);
} else {
print (i);
}
本文标签: javascriptTest If The Array Index Equals The Array ValueStack Overflow
版权声明:本文标题:javascript - Test If The Array Index Equals The Array Value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744063984a2584648.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论