Help us understand the problem. What is going on with this article?

.indexOf()で配列のindexが取得できないとき

More than 1 year has passed since last update.

indexOf()でindexが取得できない

var array = ['hoge', 'huga', 'hoho'];

のような単純な配列は.indexOf()で簡単に取得できますが

var hash = [
  {number: 1, name: 'hoge'},
  {number: 2, name: 'huga'}
];

のような連想配列(ハッシュ)では、例えば「nameが'huga'である要素のindex」は取得できません。

解決方法

reactjs - Finding the array index of an object with Javascript/React.js - Stack Overflowを参考にしました。
日本語で書いておきましたがほぼ同じ内容です。
reactのコードの書き方での説明ですが難しくないです。

連想配列で「nameが'huga'である要素のindex」を取得したいときはまず

function getIndex(value, arr, prop) {
    for(var i = 0; i < arr.length; i++) {
        if(arr[i][prop] === value) {
            return i;
        }
    }
    return -1; //値が存在しなかったとき
}

という、for文で繰り返し処理をする関数をつくって

var index = getIndex('huga', hash, 'name');

とすると、目的のindexを取得することができます。

追記

2017/3/11
@ygknさんからコメントをいただきました。
array.findIndex()を使うと簡単にindexが取得できるそうです!
ありがとうございます!

var index = hash.findIndex(({name}) => name === 'huga');
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away