I have an array with pairs of numbers and need to find matching pairs within the array
numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5]... ]
I want to be able to find 1,4
. Is there a way to find this array without relying on numberStore[4]
?
I have an array with pairs of numbers and need to find matching pairs within the array
numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5]... ]
I want to be able to find 1,4
. Is there a way to find this array without relying on numberStore[4]
?
- How often do you need to perform this search? – Phil Commented Dec 16, 2018 at 23:26
-
1
numberStore.find(([a, b]) => a === 1 && b === 4)
? in the same way usemap
to update needed elements – muradm Commented Dec 16, 2018 at 23:27 - Also, what exactly do you mean by "find"? Do you want the index or just to know if the pair exists? Does the order of the pair matter? – Phil Commented Dec 16, 2018 at 23:28
- 1 Need to perform search frequently and need to know if it exists – zadubz Commented Dec 16, 2018 at 23:29
3 Answers
Reset to default 4Since you need to perform this search frequently, I would build a hashed set to avoid mapping and searching over and over. For example
const numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5] ]
const hashedSet = new Set(numberStore.map(pair => pair.toString()))
// looks like ["0,0", "1,1", "1,2", "1,3", etc]
console.log([...hashedSet])
const search = (find) => {
return hashedSet.has(find.toString())
}
console.info('Find [1,4]', search([1,4]))
console.info('Find [4,1]', search([4,1]))
I've used Array.prototype.toString()
as the hashing function but you could substitute anything there that creates a unique and parable entity for each pair.
Use Array.prototype.find()
:
var numberStore = [
[0, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5]
];
var oneFour = numberStore.find(function([a, b]) {
return a == 1 && b == 4;
});
console.log(oneFour);
Or if you prefer ES6 arrow syntax:
var numberStore = [
[0, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5]
];
var oneFour = numberStore.find(([a, b]) => a == 1 && b == 4);
console.log(oneFour);
Another alternative is using the method some() to test elements for a condition.
var numberStore = [
[0,0],
[1,1],
[1,2],
[1,3],
[1,4],
[1,5]
];
var exists = numberStore.some(([a, b]) => a === 1 && b === 4);
console.log(exists ? "Pair [1,4] exists" : "Pair [1,4] don't exists");
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745650543a4638237.html
评论列表(0条)