Reputation: 191
I have an array of hashes, how can I get the location of a hash set in the array?
In below example I like to find where on the path a certain location is but it results in a 'not found'
var path = [{x: 42, y: 8}, {x: 42, y: 7}, {x: 42, y: 6}];
var location = {x: 42, y: 6};
var a = path.indexOf(location); // this result is -1
Upvotes: 2
Views: 120
Reputation: 144729
That's because the location
object and the corresponding object in the array point to different locations in memory and are not considered equal by JavaScript interpreter, i.e even {} === {}
results in false
as these are 2 unique objects, but:
var a = {}, b = a;
if (a === b) // true
Note that is not the case for primitive values like numbers.
For filtering the corresponding object you should iterate through the array and compare each element's x and y properties against the x and y properties of the location
object, something like:
var index = -1;
var matched = path.filter(function(el, i) {
var matched = location.x === el.x && location.y === el.y;
if (matched) index = i;
return matched;
}); // [0]
Upvotes: 3
Reputation: 4494
Just to add to the solutions options, you can use Lodash, or a custom array find function to iterate on the set and find the object you want.
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = {
equal: function(point) {
if (point.x == this.x && point.y == this.y) {
return true;
}
return false;
}
}
point1 = new Point(6,1);
console.log([
new Point(4,0),
new Point(6,1),
new Point(8,12)].findIndex(
function(element, index, array){
return element.equal(point1);
}));
>> 1
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false },
{ 'user': 'pebbles', 'age': 1, 'active': true }
];
// using the `_.matches` callback shorthand
_.findIndex(users, { 'user': 'fred', 'active': false });
// → 1
Upvotes: 1
Reputation: 262
It depends what exactly you want. If you want to compare against a specific object you are already doing it right. For example:
var foo = { x: 1, y: 3 };
var not_foo = { x: 1, y: 3 };
var arrayOfThings = [foo, { x:3, y:4 }];
// this will work because foo is in there
var index = arrayOfThings.indexOf(foo);
// this will not work because not_foo is not in there
var fails = arrayOfThings.indexOf(not_foo);
If you want to find a identical object you have to get tricky. You could use a library, such as underscore
which has both a filter, and find method which could be applicable. You could also use something like:
var foo = { x: 1, y: 3 };
var not_foo = { x: 1, y: 3 };
var arrayOfThings = [foo, { x:3, y:4 }];
arrayOfThings.forEach(function(obj){
if (obj.x == foo.x && obj.y == foo.y) {
// we found a match so do something I guess!
}
});
Upvotes: 0