3

How can i get all index of array,

[  
   {  
      "name":"aloha",
      "age":"18"
   },
   {  
      "name":"hello word"
   },
   {  
      "name":"John Doe",
      "age":"28"
   }
]

Output should be like [0,1,2]

2
  • 2
    Please refer this AlexC stackoverflow.com/help/how-to-ask. Consider trying something before asking question. Commented May 10, 2019 at 9:54
  • every array index start form zero and end at the number one less than the length of array. what you want to ask, ask properly Commented May 10, 2019 at 9:57

3 Answers 3

7

Simplest way would be to (see this post):

let a = [{1: 'x'}, {1: 'y'}, {1: 'z'}]
let b = Array.from(a.keys())
console.log(b)

and the naive solution is by calling map((_, i) => i)) on your array:

let a = [{1: 'x'}, {1: 'y'}, {1: 'z'}]
let b = a.map((_, i) => i)
console.log(b)

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Object.keys also to check keys index of any object.

let a = [
        {
        'name' : "aloha",
        "age": "18"
        },
        {
        "name": "hello word"
        },
        {
        "name": "John Doe",
        "age" : "28"
    }]
    
console.log(Object.keys(a));

Comments

0

You can use forEach loop, like this example:

//The array you want to get all the indexes from
const array = [{'a':1}, {'b':2}, {'c':3}];
//All indexes array
const indexArray = [];

array.forEach((el, i) => {
    indexArray.push(i);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.