Programing

조건과 일치하는 배열 내 객체의 인덱스를 가져옵니다.

lottogame 2020. 3. 30. 08:43
반응형

조건과 일치하는 배열 내 객체의 인덱스를 가져옵니다.


다음과 같은 배열이 있습니다.

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

전체 배열을 반복하지 않고 조건과 일치하는 객체의 인덱스를 어떻게 얻을 수 있습니까?

예를 들어, 주어진 prop2=="yutu"index을 얻고 싶습니다 1.

나는 보았지만 .indexOf()같은 간단한 배열에 사용된다고 생각합니다 ["a1","a2",...]. 또한 확인 $.grep()했지만 인덱스가 아닌 객체를 반환합니다.


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

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

대부분의 최적화와 마찬가지로 실제로 필요할 때만주의해서 적용해야합니다.


배열을 따라 반복하지 않고 조건과 일치하는 객체의 인덱스를 어떻게 얻을 수 있습니까?

당신은 무언가 를 배열을 통해 반복해야합니다 (적어도 한 번).

조건이 많이 바뀌면 반복해서 객체가 조건과 일치하는지 확인해야합니다. 그러나 ES5 기능이있는 시스템 (또는 shim을 설치 한 경우)에서 해당 반복을 상당히 간결하게 수행 할 수 있습니다.

var index;
yourArray.some(function(entry, i) {
    if (entry.prop2 == "yutu") {
        index = i;
        return true;
    }
});

new (ish) Array#some함수를 사용합니다. 이 함수는 사용자가 제공 한 함수가 true를 반환 할 때까지 배열의 항목을 반복합니다. 내가 제공 한 함수는 일치하는 항목의 색인을 저장 한 다음 true반복을 중지하기 위해 반환 합니다.

또는 물론 for루프를 사용하십시오 . 다양한 반복 옵션은 이 다른 답변 에서 다룹니다 .

그러나이 조회에 항상 동일한 속성을 사용하고 속성 값이 고유 한 경우 한 번만 반복하고 객체를 만들어 매핑 할 수 있습니다.

var prop2map = {};
yourArray.forEach(function(entry) {
    prop2map[entry.prop2] = entry;
});

또는 다시 for루프 또는 다른 옵션을 사용할 수 있습니다 .

그런 다음로 항목을 찾아야 할 경우 다음 prop2 = "yutu"을 수행 할 수 있습니다.

var entry = prop2map["yutu"];

나는 이것을 "교차 색인"이라고 부른다. 당연히 항목을 제거하거나 추가하거나 prop2값을 변경하는 경우 매핑 개체도 업데이트해야합니다.


TJ Crowder가 말한 바와 같이, 매번 어떤 종류의 숨겨진 반복이있을 것입니다 .

var index = _.findIndex(array, {prop2: 'yutu'})

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

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을 얻습니다.


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

위의 많은 솔루션을 보았습니다.

여기서는 map 함수를 사용하여 배열 객체에서 검색 텍스트의 색인을 찾습니다.

학생 데이터를 사용하여 답변을 설명하려고합니다.

  • 1 단계 : 학생들을위한 배열 객체를 만듭니다 (선택 사항은 자신의 배열 객체를 만들 수 있습니다).
    var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];

  • 2 단계 : 텍스트를 검색 할 변수 만들기
    var studentNameToSearch = "Divya";

  • 3 단계 : 일치하는 인덱스를 저장할 변수를 만듭니다 (여기서는 map 함수를 사용하여 반복합니다).
    var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);

var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];

var studentNameToSearch = "Divya";

var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);

console.log(matchedIndex);

alert("Your search name index in array is:"+matchedIndex)


왜 정확하게 반복하고 싶지 않습니까? 새로운 Array.prototype.forEach 는이 목적에 적합합니다!

원하는 경우 이진 검색 트리를 사용하여 단일 메소드 호출을 통해 찾을 수 있습니다. 이것은 JS의 BTree 및 Red black Search 트리 ( https://github.com/vadimg/js_bintrees )의 깔끔한 구현 이지만 동시에 인덱스를 찾을 수 있는지 확실하지 않습니다.


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색인을 찾지 못하면를 반환 합니다.


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

var list =  [
                {prop1:"abc",prop2:"qwe"},
                {prop1:"bnmb",prop2:"yutu"},
                {prop1:"zxvz",prop2:"qwrq"}
            ];

var findProp = p => {
    var index = -1;
    $.each(list, (i, o) => {
        if(o.prop2 == p) {
            index = i;
            return false; // break
        }
    });
    return index; // -1 == not found, else == index
}

Georg는 이미 ES6에 Array.findIndex가 있다고 언급했습니다. 그리고 다른 답변은 Array.some 메소드를 사용하는 ES5에 대한 해결 방법입니다.

하나 더 우아한 접근법은

var index;
for(index = yourArray.length; index-- > 0 && yourArray[index].prop2 !== "yutu";);

동시에 강조하고 싶습니다. Array.some은 이진 또는 다른 효율적인 검색 기술로 구현 될 수 있습니다. 따라서 일부 브라우저에서는 for 루프보다 성능이 우수 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/15997879/get-the-index-of-the-object-inside-an-array-matching-a-condition

반응형