객체 배열에서 속성이 검색과 일치하는 객체의 색인을 찾는 가장 빠른 방법
나는 이것을하기위한 효율적인 방법을 찾으려고 약간의 서핑을하고 있지만 아무데도 얻지 못했습니다. 다음과 같은 객체 배열이 있습니다.
array[i].id = some number;
array[i].name = some name;
내가하고 싶은 것은 id가 0,1,2,3 또는 4와 같은 객체의 INDEXES를 찾는 것입니다. 나는 다음과 같이 할 수 있다고 가정합니다.
var indexes = [];
for(i=0; i<array.length; i++) {
(array[i].id === 0) ? { indexes[0] = i }
(array[i].id === 1) ? { indexes[1] = i }
(array[i].id === 2) ? { indexes[2] = i }
(array[i].id === 3) ? { indexes[3] = i }
(array[i].id === 4) ? { indexes[4] = i }
}
이것이 효과가 있지만, 특히 array.length가 클 수있는 경우 상당히 비싸고 느리게 보입니다 (추악한 것은 아닙니다). 이것을 조금 가려내는 방법에 대한 아이디어가 있습니까? 어떻게 든 array.indexOf를 사용하려고 생각했지만 구문을 강제하는 방법을 보지 못했습니다. 이
array.indexOf(this.id === 0);
예를 들어, 예상대로 undefined를 반환합니다. 미리 감사드립니다!
"map"과 같은 고차 함수를 사용하고 싶을 수도 있습니다. 'field'속성으로 검색한다고 가정합니다.
var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];
배열에서 요소 인덱스를 찾는 가장 간단하고 쉬운 방법입니다.
ES5 구문 : [{id:1},{id:2},{id:3},{id:4}].findIndex(function(obj){return obj.id == 3})
ES6 구문 : [{id:1},{id:2},{id:3},{id:4}].findIndex(obj => obj.id == 3)
새로운 Array 메소드 .filter () 는 다음과 같이 작동합니다.
var filteredArray = array.filter(function (element) {
return element.id === 0;
});
jQuery는 .grep ()으로도 이를 수행 할 수 있습니다.
편집 :이 두 기능 모두 후드에서 반복된다는 점은 언급 할 가치가 있습니다. 기능과 눈에 띄는 필터 기능을 롤링하는 것 사이에는 눈에 띄는 성능 차이가 없지만 휠을 다시 발명 해야하는 이유는 무엇입니까?
array.forEach(function (elem, i) { // iterate over all elements of array
indexes[elem.id] = i; // take the found id as index for the
}); // indexes array and assign i
결과는 id에 대한 조회 목록입니다. 주어진 ID로 레코드의 인덱스를 얻습니다.
var indices = [];
var IDs = [0, 1, 2, 3, 4];
for(var i = 0, len = array.length; i < len; i++) {
for(var j = 0; j < IDs.length; j++) {
if(array[i].id == ID) indices.push(i);
}
}
일반 배열을 사용하는 답변이 없기 때문에 find:
var one = {id: 1, name: 'one'};
var two = {id: 2, name:'two'}
var arr = [one, two]
var found = arr.find((a) => a.id === 2)
found === two // true
arr.indexOf(found) // 1
성능에 관심이 있다면 찾기 또는 필터링 또는 매핑 하거나 위에서 설명한 방법 중 하나를 사용하지 마십시오.
다음은 가장 빠른 방법을 보여주는 예입니다. 여기에 실제 시험에 대한 링크입니다
셋업 블록
var items = []
for(var i = 0; i < 1000; i++) {
items.push({id: i + 1})
}
var find = 523
가장 빠른 방법
var index = -1
for(var i = 0; i < items.length; i++) {
if(items[i].id === find) {
index = i;
break;
}
}
느린 방법
items.findIndex(item => item.id === find)
가장 느린 방법
items.map(item => item.id).indexOf(find);
ES6를 사용하는 새로운 방법
let picked_element = array.filter(element => element.id === 0);
const index = array.findIndex(item => item.id === 'your-id');
이것은 id === your-id 인 배열의 항목 색인을 가져옵니다.
array = [ {id:1}, {id:2} ];
const index = array.findIndex(item => item.id === 2);
console.log(index);
테스트 콜백으로 간단한 반복자를 만들 수있는 것처럼 들립니다. 이렇게 :
function findElements(array, predicate)
{
var matchingIndices = [];
for(var j = 0; j < array.length; j++)
{
if(predicate(array[j]))
matchingIndices.push(j);
}
return matchingIndices;
}
그런 다음 다음과 같이 호출 할 수 있습니다.
var someArray = [
{ id: 1, text: "Hello" },
{ id: 2, text: "World" },
{ id: 3, text: "Sup" },
{ id: 4, text: "Dawg" }
];
var matchingIndices = findElements(someArray, function(item)
{
return item.id % 2 == 0;
});
// Should have an array of [1, 3] as the indexes that matched
mongoDB 및 Robomongo에 대한 Tejs의 답변에 적응하기
matchingIndices.push(j);
에
matchingIndices.push(NumberInt(j+1));
ES6 map기능 사용 :
let idToFind = 3;
let index = someArray.map(obj => obj.id).indexOf(idToFind);
위의 모든 위대한 답변과 요약에 대한 내 답변을 요약하면 일부 의견에서 모든 색인을 찾았습니다.
- 첫 번째 발생 색인을 반환합니다.
const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 2 }];
const idYourAreLookingFor = 2;
//ES5
//Output: 1
array.map(function (x) { return x.id; }).indexOf(idYourAreLookingFor);
//ES6
//Output: 1
array.findIndex(obj => obj.id === idYourAreLookingFor);
- To return the index array of all occurrences, using reduce.
const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 2 }]
const idYourAreLookingFor = 2;
//ES5
//Output: [1, 4]
array.reduce(function (acc, obj, i) {
if (obj.id === idYourAreLookingFor)
acc.push(i);
return acc;
}, []);
//ES6
//Output: [1, 4]
array.reduce((acc, obj, i) => (obj.id === idYourAreLookingFor) ? acc.concat(i) : acc, [])
As I can't comment yet, I want to show the solution I used based on the method Umair Ahmed posted, but when you want to search for a key instead of a value:
[{"a":true}, {"f":true}, {"g":false}]
.findIndex(function(element){return Object.keys(element)[0] == "g"});
I understand that it doesn't answer the expanded question, but the title doesn't specify what was wanted from each object, so I want to humbly share this to save headaches to others in the future, while I undestart it may not be the fastest solution.
I've created a tiny utility called super-array where you can access items in an array by a unique identifier with O(1) complexity. Example:
const SuperArray = require('super-array');
const myArray = new SuperArray([
{id: 'ab1', name: 'John'},
{id: 'ab2', name: 'Peter'},
]);
console.log(myArray.get('ab1')); // {id: 'ab1', name: 'John'}
console.log(myArray.get('ab2')); // {id: 'ab2', name: 'Peter'}
var test = [
{id:1, test: 1},
{id:2, test: 2},
{id:2, test: 2}
];
var result = test.findIndex(findIndex, '2');
console.log(result);
function findIndex(object) {
return object.id == this;
}
will return index 1 (Works only in ES 2016)
I like this method because it's easy to compare to any value in the object no matter how deep it's nested.
while(i<myArray.length && myArray[i].data.value!==value){
i++;
}
// i now hows the index value for the match.
console.log("Index ->",i );
'Programming' 카테고리의 다른 글
| 신속한 대의원? (0) | 2020.07.01 |
|---|---|
| 카운트 다운하는 것보다 카운트 다운하는 것이 더 빠릅니까? (0) | 2020.07.01 |
| Java로 맵을 인쇄하십시오 (0) | 2020.07.01 |
| node.js로 고유 ID를 생성하는 방법 (0) | 2020.07.01 |
| 유닉스 정렬로 여러 키 정렬 (0) | 2020.07.01 |