466

私はこのような配列を持っています:

[{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"},...]

配列全体を反復せずに、条件に一致するオブジェクトのインデックスを取得するにはどうすればよいですか?

たとえば、 が与えられた場合、prop2=="yutu"index を取得したいとします1

見まし.indexOf()たが、のような単純な配列に使用されていると思います["a1","a2",...]。私もチェック$.grep()しましたが、これはインデックスではなくオブジェクトを返します。

4

15 に答える 15

1029

2016年現在、これにはArray.findIndex(ES2015 / ES6標準)を使用することになっています:

a = [
  {prop1:"abc",prop2:"qwe"},
  {prop1:"bnmb",prop2:"yutu"},
  {prop1:"zxvz",prop2:"qwrq"}];
    
index = a.findIndex(x => x.prop2 ==="yutu");

console.log(index);

Google Chrome、Firefox、Edge でサポートされています。Internet Explorer の場合、リンク先のページにポリフィルがあります。

パフォーマンスノート

関数呼び出しはコストがかかるため、非常に大きな配列では、単純なループの方が よりもはるかに優れたパフォーマンスを発揮しますfindIndex:

let test = [];

for (let i = 0; i < 1e6; i++)
    test.push({prop: i});


let search = test.length - 1;
let count = 100;

console.time('findIndex/predefined function');
    let fn = obj => obj.prop === search;

    for (let i = 0; i < count; i++)
        test.findIndex(fn);
console.timeEnd('findIndex/predefined function');


console.time('findIndex/dynamic function');
    for (let i = 0; i < count; i++)
        test.findIndex(obj => obj.prop === search);
console.timeEnd('findIndex/dynamic function');


console.time('loop');
    for (let i = 0; i < count; i++) {
        for (let index = 0; index < test.length; index++) {
            if (test[index].prop === search) {
                break;
            }
        }
    }
console.timeEnd('loop');

ほとんどの最適化と同様に、これは注意して、実際に必要な場合にのみ適用する必要があります。

于 2013-04-14T10:22:18.187 に答える
26

TJ Crowderが言ったことは、常に何らかの隠された反復があり、lodashを使用すると次のようになります。

var index = _.findIndex(array, {prop2: 'yutu'})
于 2015-02-03T13:44:02.173 に答える
18
var CarId = 23;

//x.VehicleId property to match in the object array
var carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);

また、基本的な配列番号については、次のこともできます。

var numberList = [100,200,300,400,500];
var index = numberList.indexOf(200); // 1

配列内に値が見つからない場合は -1 が返されます。

于 2017-08-16T23:35:35.177 に答える
13
var index;
yourArray.some(function (elem, i) {
    return elem.prop2 === 'yutu' ? (index = i, true) : false;
});

配列のすべての要素を反復処理します。条件が一致しない場合は、インデックスと true または false を返します。

true の明示的な戻り値 (またはブール値の結果が true になる値) が重要です。0 (Boolean(0) === false) のインデックスが存在する可能性があるため、単一の割り当てでは十分ではありません。これはエラーにはなりませんが、反復の中断を無効にします。

編集

上記のさらに短いバージョン:

yourArray.some(function (elem, i) {
    return elem.prop2 === 'yutu' && ~(index = i);
});
于 2015-04-08T17:50:23.950 に答える
3

次の方法でArray.prototype.some()を使用できます(他の回答で述べたように):

https://jsfiddle.net/h1d69exj/2/

function findIndexInData(data, property, value) {
    var result = -1;
    data.some(function (item, i) {
        if (item[property] === value) {
            result = i;
            return true;
        }
    });
    return result;
}
var data = [{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"}]



alert(findIndexInData(data, 'prop2', "yutu")); // shows index of 1
于 2015-03-19T21:51:54.583 に答える
3
function findIndexByKeyValue(_array, key, value) {
    for (var i = 0; i < _array.length; i++) { 
        if (_array[i][key] == value) {
            return i;
        }
    }
    return -1;
}
var a = [
    {prop1:"abc",prop2:"qwe"},
    {prop1:"bnmb",prop2:"yutu"},
    {prop1:"zxvz",prop2:"qwrq"}];
var index = findIndexByKeyValue(a, 'prop2', 'yutu');
console.log(index);
于 2017-03-01T06:14:58.000 に答える
0

Array.reduce() を使用したワンステップ - jQuery なし

var items = [{id: 331}, {id: 220}, {id: 872}];

var searchIndexForId = 220;
var index = items.reduce(function(searchIndex, item, index){
  if(item.id === searchIndexForId) { 
    console.log('found!');
    searchIndex = index;
  }
  return searchIndex;
}, null);

nullインデックスが見つからなかった場合に返されます。

于 2016-12-05T14:12:24.433 に答える
0

正確に反復したくないのはなぜですか?新しいArray.prototype.forEachは、こ​​の目的に最適です!

必要に応じて、バイナリ検索ツリーを使用して、単一のメソッド呼び出しで検索できます。これは JS での BTree と Red black Search ツリーのきちんとした実装です ( https://github.com/vadimg/js_bintrees ) が、同時にインデックスを見つけることができるかどうかはわかりません。

于 2013-04-14T10:18:10.990 に答える