7

I have an array that looks like so:

var skillsets = [
  {id: 'one', name: 'george'},
  {id: 'two', name: 'greg'},
  {id: 'three', name: 'jason'},
  {id: 'four', name: 'jane'},
];

what I would like to do is find the row based on a value given in the form of an id with Javascript. For instance, if I put "id='two'" into the function, I'd like "1" to be returned as the row.

I know for a single row array, skillsets.indexOf['value'] would work, but that won't work for this JSON set.

How can I achieve this?

EDIT:

Skills = React.createClass({

    getInitialState: function() {
      return { id: 'default' };
    },

    getIndex(value, arr, prop) {
    for(var i = 0; i < arr.length; i++) {
        if(arr[i][prop] === value) {
            return i;
        }
    }
    return -1; //to handle the case where the value doesn't exist
    },

    render: function() {

        var index = getIndex(id, skillsets, 'id');

        return (

            <section id="three" className="main style1 special">
                <div className="container">

                    <SkillsHeader skillsets={skillsets[index]}/>
                    {index}
                    <SkillsDetails details={details}/>
                    {index}

                </div>
            </section>

        );

    }
});
0

2 Answers 2

14

A simple for loop wrapped in a reusable function is good enough:

function getIndex(value, arr, prop) {
    for(var i = 0; i < arr.length; i++) {
        if(arr[i][prop] === value) {
            return i;
        }
    }
    return -1; //to handle the case where the value doesn't exist
}

Here, value is the value you want to match against, arr is the array of objects, and prop is the property of each iterable of the array which should match the value.

You can use this function for any json with the structure you mentioned. In your specific case, call it like this:

var index = getIndex('one', skillsets, 'id');
Sign up to request clarification or add additional context in comments.

8 Comments

Or perhaps return -1 if not found, to match what indexOf() does?
Yes, that would be better!
saying getIndex is undefined
most probably you are using it before declaring it. Show us your code.
I just included it in my original Q
|
5

Lodash has a findIndex method that does exactly this.

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

_.findIndex(users, function(o) { return o.user == 'barney'; });
// → 0

// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
// → 1

// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// → 0

// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// → 2

But I think ES6 just supports the lambda version anyway (?) it's in the doc on the flux page:

 removeTodo (id) {
        let index = this.todos.findIndex(todo => todo.get('id') === id);

        // remove the todo with the ID of id, but only if we have it to begin with
        this.todos = index > -1 ?
            this.todos.remove(index) :
            this.todos;
    },

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.