How do I get the index of object in array using angular?
An easy and elegant solution is to use _.isEqual, which performs a deep comparison using lodash library
Npm Package -- https://www.npmjs.com/package/lodash
const a = [
{ firstName: "Adam", LastName: "Howard" },
{ firstName: "Ben", LastName: "Skeet" },
{ firstName: "Joseph", LastName: "Skeet" }
];
const find = { firstName: "Joseph", LastName: "Skeet" }
index = a.findIndex(x => _.isEqual(x, find));
console.log(index);
As mdn says:
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
If you have array of objects like this, then try to use findIndex
:
const a = [
{ firstName: "Adam", LastName: "Howard" },
{ firstName: "Ben", LastName: "Skeet" },
{ firstName: "Joseph", LastName: "Skeet" }
];
let index = a.findIndex(x => x.LastName === "Skeet");
console.log(index);
Adding to the answer of @StepUp (and please select his answer as best, as it replies the question greatly):
Finding the index is not related to Angular, it is rather Vanilla JavaScript.
In your case, you need a function that has as parameter the newDatum
"needle" to be searched in the array "haystack" using findIndex:
var getNewDatumIndex = (array, newDatumNeedle) => {
return array.findIndex(x => x.newDatum === newDatumNeedle);
}
You can also add the method in the array prototype if you want, in order to ommit the first argument:
Array.prototype.getNewDatumIndex = (newDatumNeedle) => {
return this.findIndex(x => x.newDatum === newDatumNeedle);
}