Reputation: 127
Below is my sample code that pushes into VacanciesWithSavedSearches array by checking if the item does not already exist.
if ($scope.VacanciesWithSavedSearches.indexOf(value) == -1) {
$scope.VacanciesWithSavedSearches.push({
type: "Saved Searches",
title: value.title,
value: value.id
});
}
How do I change the above by replacing indexOf with the actually property value, e.g Add item to the list VacanciesWithSavedSearches if the list do not contain another item.id=123
Upvotes: 4
Views: 2362
Reputation: 32175
If your array was an array of numbers or primitives you could do .indexOf(value) == -1
but it's an array of objects so you can't test it with .indexOf()
method, you can use .some()
method to test over the existence of your object in the array.
The
some()
method tests whether at-least one element in the array passes the test implemented by the provided function.
This is how should be your code:
if (!$scope.VacanciesWithSavedSearches.some(function(v){return v.value.id === -1})) {
$scope.VacanciesWithSavedSearches.push({
type: "Saved Searches",
title: value.title,
value: value.id
});
}
Upvotes: 0
Reputation: 13356
You can use array.some:
If Ecmascript6 is not a problem:
var id = 123;
if (!$scope.VacanciesWithSavedSearches.some(vac => vac.id === id)) {
$scope.VacanciesWithSavedSearches.push({
type: "Saved Searches",
title: value.title,
value: id
});
}
With Ecmascript5, you can do it like below:
var id = 123;
if (!$scope.VacanciesWithSavedSearches.some(function(vac) { return vac.id === id; })) {
$scope.VacanciesWithSavedSearches.push({
type: "Saved Searches",
title: value.title,
value: id
});
}
Upvotes: 1
Reputation: 222657
use array.filter
var result = $scope.VacanciesWithSavedSearches.filter(t=t.id ==='123');
if(result.length === 0)
{
$scope.VacanciesWithSavedSearches.push({
type: "Saved Searches",
title: value.title,
value: value.id
});
}
Upvotes: 1