2
> var lst = ['red', 'blue', 'yellow'];
> someFunc(lst);
[('red', 0), ('blue', 1), ('yellow', 2)]

Is there any way to do this in Javascript/JQuery? I know that I can simply just make a for loop and convert each of the original list's element to what I want, but I was wondering if there was a built in way of doing this.

Thanks!

4
  • 1
    UM, you want objects? nested arrays? That output does not make sense Commented Aug 22, 2016 at 17:20
  • 1
    You mean lst.map(function(v, i) { return { value: v, index: i } } )? Commented Aug 22, 2016 at 17:21
  • Something that puts the index to each element, could be objects. Commented Aug 22, 2016 at 17:21
  • Why by the way? lst[0] is red, lst[1] is blue. lst.indexOf("yellow") is 2 Commented Aug 22, 2016 at 17:33

3 Answers 3

2

You could use Array#map and return for each item an array with the value and the index.

var lst = ['red', 'blue', 'yellow'],
    array = lst.map(function (a, i) { return [a, i]; });

console.log(array);

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

2 Comments

Yep! Except the comma should be a semi-colon, right?
No, Nina's declaring two variables, its shorthand for writing var lst ...; var array ...;
0

You can leverage the map() function that is providing you both the value and and index of each item in the array:

lst.map(function(v, i) { return { value: v, index: i }; } );

See MDN

Comments

0

With map method in ES6 :

var lst = ['red', 'blue', 'yellow'];
var array = lst.map((item, index) => [item, index])
console.log(array); // [ [ 'red', 0 ], [ 'blue', 1 ], [ 'yellow', 2 ] ]

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.