programing

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

yoursource 2022. 10. 2. 12:15
반응형

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

다음과 같은 어레이가 있습니다.

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

어레이 전체에 걸쳐 반복하지 않고 조건과 일치하는 개체의 인덱스를 가져오려면 어떻게 해야 합니까?

를 들어, 「」를 하면,prop2=="yutu", 지수를 1.

를 ..indexOf() 이렇게 것 요.["a1","a2",...]$.grep()그러나 인덱스가 아닌 객체를 반환합니다.

2016년 현재 이를 위해 (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');

대부분의 최적화와 마찬가지로 실제로 필요한 경우에만 주의를 기울여 적용해야 합니다.

오브젝트 인덱스를 (배열을 따라 반복하지 않고) 조건과 일치시키려면 어떻게 해야 합니까?

수 없습니다.배열을 반복해야 합니다(최소 1회).

조건이 많이 바뀌면 루프스루프하여 조건에 일치하는지 여부를 확인해야 합니다.단, ES5 기능이 있는 시스템(또는 Shim을 설치하는 경우)에서는 이 반복을 매우 간결하게 수행할 수 있습니다.

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

그러면 new(ish) 함수가 사용됩니다.이 함수는 지정한 함수가 true를 반환할 때까지 배열 내의 엔트리를 루프합니다.지정한 함수는 일치하는 항목의 인덱스를 저장한 다음 반환한다.true을 사용하다

물론 ,, 론, 론, 물, 물, 물, 물, 물, 물, .for루프. 다양한 반복 옵션은 이 다른 답변에 설명되어 있습니다.

그러나 이 검색에 항상 동일한 속성을 사용하고 속성 값이 고유할 경우 한 번만 루프하고 매핑할 개체를 만들 수 있습니다.

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

'(어, 하다)'를 사용할 수 .forloop 또는 기타 옵션하나).

''가 있는 하는 prop2 = "yutu"이치노

var entry = prop2map["yutu"];

저는 이것을 어레이라고 부릅니다. 또는 엔트리를 하는 경우)prop2values.values).

TJ Crowder가 말한 것처럼, 모든 곳에 숨겨진 반복이 있을 것이고, lodash와 함께 이것은 다음과 같습니다.

var index = _.findIndex(array, {prop2: 'yutu'})
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이 됩니다.

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

사용.Array.map()그리고.Array.indexOf(string)

const arr = [{
  prop1: "abc",
  prop2: "qwe"
}, {
  prop1: "bnmb",
  prop2: "yutu"
}, {
  prop1: "zxvz",
  prop2: "qwrq"
}]

const index = arr.map(i => i.prop2).indexOf("yutu");

console.log(index);

나는 위에서 많은 해결책을 봐왔다.

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

저는 학생 자료를 사용해서 제 답을 설명하겠습니다.

  • 순서 1: 학생용 어레이 오브젝트를 만듭니다(옵션으로 독자적인 어레이 오브젝트를 작성할 수 있습니다).
    var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];

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

  • 스텝 3: 일치하는 인덱스를 저장할 변수를 만듭니다(여기에서는 맵 함수를 사용하여 반복합니다).
    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.protype.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
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 x = [{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"}]
let index = x.findIndex(x => x.prop1 === 'zxvz')

또 다른 간단한 방법은 다음과 같습니다.

 function getIndex(items) {
        for (const [index, item] of items.entries()) {
            if (item.prop2 === 'yutu') {
                return index;
            }
        }
    }

const myIndex = getIndex(myArray);

이를 위한 가장 빠른 방법은 다음과 같습니다.

const products = [
  { prop1: 'telephone', prop2: 996 },
  { prop1: 'computadora', prop2: 1999 },
  { prop1: 'bicicleta', prop2: 995 },
];

const index = products.findIndex(el => el.prop2 > 1000);

console.log(index); // 1

Georg는 이미 ES6에 Array.findIndex가 있다고 언급했습니다.또한 Array.somethod를 사용하는 ES5의 회피책도 있습니다.

한층 더 우아한 어프로치가 있습니다.

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

동시에 강조하고 싶은 것은 Array.일부는 바이너리 또는 기타 효율적인 검색 기술로 구현될 수 있다는 것입니다.따라서 브라우저에 따라서는 for loop에 대한 성능이 향상될 수 있습니다.

왜 당신은 정확히 반복하고 싶지 않은가요?새로운 Array.protype.각각은 이 목적을 위해 훌륭합니다!

필요에 따라 바이너리 검색 트리를 사용하여 단일 메서드 호출을 통해 검색할 수 있습니다.이것은 JS의 BTree와 Red Black Search 트리의 깔끔한 구현입니다. https://github.com/vadimg/js_bintrees - 하지만 동시에 인덱스를 찾을 수 있을지 모르겠습니다.

Array.reduce()를 사용한1단계 - no 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인덱스를 찾을 수 없는 경우.

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
}

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

반응형