indexOf method in an object array?
I think you can solve it in one line using the map function:
const pos = myArray.map(e => e.hello).indexOf('stevie');
How to get Index of an object from an array [JavaScript]?
From DOCS
The indexOf() method returns the index within the calling String
object of the first occurrence of the specified value, starting the
search at fromIndex. Returns -1 if the value is not found.
Use findIndex
DEMO
let database = [{
name: 'James Bond',
code: '007'
},
{
name: 'El',
code: '11'
}
]
let subject = {
name: 'James Bond',
code: '007'
}
console.log(database.findIndex(x => x.name=="James Bond"))
How can I get the index of an object by its property in JavaScript?
As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
var Data = [
{id_list: 2, name: 'John', token: '123123'},
{id_list: 1, name: 'Nick', token: '312312'}
];
With this, not only can you find which one contains 'John', but you can find which contains the token '312312':
findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1
The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().
Why indexOf can find the index of my object inside array of same class objects?
First thing you gotta know about Objects (in javascript) is that they are assigned by REFERENCE and NOT by value. With that in mind, every time you declare a variable and assign it with a javascript object, you are storing the reference to the object's address in memory.
when you use indexOf with javascript objects, you are comparing memory address of the OBJECTS and not from the CLASS. Everytime you use NEW with a class (that returns a javascript object) you are instantiating an object from a specific class and returning the address of the OBJECT that you can store at a variable (in this case, it is 'n').
When you use indexOf(n), the function will search for the memory address of the object stored in 'n' and return it's index location inside the array. The others objects you created inside the loop (even being from the same class) will have an unique memory address for each one.
The reason why it will work with both == and === is that When you use === you will compare objects address to check if they are equal. When you use ==, it will make a type cast before comparing. Example, if you compare a string with a number using ==, it will convert one type into another and then will compare their values.
Get the index of the object inside an array, matching a condition
As of 2016, you're supposed to use Array.findIndex
(an ES2015/ES6 standard) for this:
a = [
{prop1:"abc",prop2:"qwe"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
index = a.findIndex(x => x.prop2 ==="yutu");
console.log(index);
Using indexOf() method for ArrayList of objects
First using stream we will Iterate through hospitals list,
find out the hospital from the list whose name equals currentHospital
name, take out the first result using findFirst
.
Since the result may be or may not be available it returns Optional.
So on Optional, we will say if it's (the hospital object which we were looking for) present we will get the hospital out of it using the get
method
Optional<Hospital> result = hospitals.stream().filter(h -> h.nameHospital.equals(currentHospital)).findFirst();
if(result.isPresent()){
Hospital hospital = result.get();
}
How do I get the index of object in array using angular?
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);
Array.indexOf() - of a document containing a field of given value [JavaScript]
You can use Array#findIndex
.
const arr = [
{ name: 'abc', age: 17 },
{ name: 'xyz', age: 18 },
{ name: 'pqr', age: 19 },
];
let idx = arr.findIndex(({age})=>age===18);
console.log(idx);
In an array of objects, fastest way to find the index of an object whose attributes match a search
Maybe you would like to use higher-order functions such as "map".
Assuming you want search by 'field' attribute:
var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];
Related Topics
How to Connect to SQL Server Database from JavaScript in the Browser
Backslashes - Regular Expression - JavaScript
Preloading Images With JavaScript
Whats the Best Way to Update an Object in an Array in Reactjs
Jspdf Can't Get Any Styling to Work
Simulate Background-Size:Cover on <Video> or <Img>
How to Inject CSS into Webpage Through Chrome Extension
CSS Transitions on New Elements
Scraping JavaScript Website in R
Dynamically Load a JavaScript File
How to Count String Occurrence in String
Graph Visualization Library in JavaScript
Arrow Function Without Curly Braces
Difference Between Two Dates in Years, Months, Days in JavaScript
How to Use the Spacing Utility Classes in Bootstrap