2

I have an array of elements in Javascript

var axes = [{id: "a"}, {id: "b"}]

and I have one of these items in a variable

var axis = {id: "b"}

I wanted a one liner in JavaScript (similar to the Linq one liners I can do in C#) where I will get the index of the array in which this element exists. So, in this example I will get the answer 1.

How is this possible?

Satpal
  • 132,252
  • 13
  • 159
  • 168
Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
  • `{id="b"}` isn't proper JavaScript. You want `{id:"b"}`. – Andy May 21 '14 at 09:56
  • see this question http://stackoverflow.com/questions/11258077/how-to-find-index-of-an-object-by-key-and-value-in-an-javascript-array – 111 May 21 '14 at 10:25

2 Answers2

1

You can use array prototype map method:

var axisIndex = axes.map(function(x) {return x.id; }).indexOf(axis.id);

https://stackoverflow.com/a/16100446/1414562

And to support older browsers, you could use the jQuery's way:

var axisIndex = $.inArray(axis.id, $.map(axes, function(x){return x.id}));
Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

It looks like you want to create a new axis object that looks the same as one of the elements in the axes array, but isn't actually an element of the axes array. If this is the case, the indexOf method won't work because it would expect to find the exact object you're searching for in the array.

There are ways of doing this - it would usually involve more than one line though (the one line restriction seems fairly trivial). However, I've found a solution, despite it looking rather ugly, and better suited to a code golfing problem than real live code.

axes.indexOf(axes.filter(function(el) {if (el.id === axis.id) return true; }).shift());

Pudge601
  • 2,048
  • 1
  • 12
  • 11