Find Index Of The Object An Array Angularjs
Solution 1:
You could use Array.findIndex
in the latest browsers, but there's no support for this in Internet Explorer, only Edge
let $scope = {};
$scope.records = [
{
"Name" : "Alfreds Futterkiste",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbköp",
"Country" : "Sweden"
},
{
"Name" : "Centro comercial Moctezuma",
"Country" : "Mexico"
},
{
"Name" : "Ernst Handel",
"Country" : "Austria"
}
];
let index = $scope.records.findIndex( record => record.Country === "Austria" );
console.log(index); // 3
For support in IE9 and up, you could use Array.some
instead
var $scope = {};
$scope.records = [{
"Name": "Alfreds Futterkiste",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"Country": "Mexico"
}, {
"Name": "Ernst Handel",
"Country": "Austria"
}];
var index = -1;
$scope.records.some(function(obj, i) {
return obj.Country === "Austria" ? index = i : false;
});
console.log(index);
Solution 2:
You can use array.findIndex
for this:
var d = [{
"Name": "Alfreds Futterkiste",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"Country": "Mexico"
}, {
"Name": "Ernst Handel",
"Country": "Austria"
}];
var searchCountry = "Austria"var index = d.findIndex(x=>x.Country === searchCountry)
console.log(index)
Note: array.findIndex is a part of ES6.
Solution 3:
Use findIndex method -
var index = $scope.records.findIndex(x=>x.Country==='Austria')
Solution 4:
functiongetIndexByCountryName(country)
var found = $scope.records.find(function(item){return item.Country === country});
return $scope.records.indexOf(found);
}
Solution 5:
You can do which returns the countries and then finds the country.
$scope.records.map((item) => { return item.Country;}).indexOf('Austria')
The problem with the above code iterates once through each element to generate a map and then finds the index. You can use a simple for loop:
var index = (arr, k, v) => {
var i = -1;len = (arr || []).length;
for (i = 0; i < len; i++) {
if (arr[i][k] === v)
return i;
}
return-1;
}
I noticed a lot of findIndex solutions. Please note: FindIndex method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet as per MDN.
You can use the polyfill for findIndex(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) and use the findIndex solution that others suggested. If you do not want to use the polyfill you can use the map and indexOf that I put as solution.
Post a Comment for "Find Index Of The Object An Array Angularjs"