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?

2
  • {id="b"} isn't proper JavaScript. You want {id:"b"}. Commented May 21, 2014 at 9:56
  • see this question stackoverflow.com/questions/11258077/… Commented May 21, 2014 at 10:25

2 Answers 2

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}));
Sign up to request clarification or add additional context in comments.

Comments

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());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.