D_S D_S - 23 days ago 6
Javascript Question

Understanding For loops in javascript - printing index of values in Array

Hey guys I'm trying to get my head around for loops.

I'm trying to print the indexes of values of an array. When I do this:

let a = [1,2,3,4,5];

var findIdx = function (arr) {
for (let i = 0 ; i < arr.length; i++) {
var indexes = [];
var index = arr[i];
console.log(index);
return indexes.push(index);
}
return indexes;
}

console.log(findIdx(a));
// => 0,1 // return


Which is not what I want, I would like to get the index of those values. Furthermore, my
return
is returning
1
. I would like an array made of those indexes. What am I'm missing?

When I do a
for in
loop I get what I want on my console, but I'm still returning the value where that index is found.

let a = [1,2,3,4,5];


var findIdxWithForIn = function (arr) {
var indexes = [];
for (i in arr) {
var index = i;
console.log(index);
return indexes.push(index);
}
return indexes
}

console.log(findIdxWithForIn(a));
// => 0, 1 // return


TL;DR: Here is a jsfiddle with the above code. Thanks in advanced.

EDIT1: Changed code with proposed changes.
EDIT1: TL;DR: I would like just to all the indexes inside that array

Answer

You are printing var index which is not an index it is element in array:

var index = arr[i];
console.log(index);

You need to get index so var index = i;. Because i in for loop is actual index. You can also use arr.indexOf(...); to get index of specific element.