Home > other >  i want to print index of all elements without using forEach or filter or map
i want to print index of all elements without using forEach or filter or map

Time:03-13

here is my code it is giving me the same index number of the element.

i want it like this 0,1,2,3,4,5,6

let as=[1, 2, 3, 4, 5, 5,5]

for(let i=0;i<as.length;i  ){
  console.log(as[i], as.indexOf(as[i]))
}

here is my output

1 0
2 1
3 2
4 3
5 4
5 4
5 4

CodePudding user response:

Create an array you can push the indexes into, and then create a string with join.

const as = [1, 2, 3, 4, 5, 5, 5];
let out = [];

for (let i = 0; i < as.length; i  ) {
  out.push(i);
}

console.log(out.join(','));

CodePudding user response:

Try this:

let as=[1, 2, 3, 4, 5, 5,5]

for(let i=0;i<as.length;i  ){
  console.log(as[i], as.indexOf(as[i],i))
}

Explaination: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

  • Related