I have this array of objects:
var frequencies = [{id:124,name:'qqq'},
{id:589,name:'www'},
{id:45,name:'eee'},
{id:567,name:'rrr'}];
I need to get an object from the array above by the id
value.
For example I need to get the object with id = 45.
I tried this:
var t = frequencies.map(function (obj) { return obj.id==45; });
But I didn't get the desired object.
How can I implement it using JavaScript prototype functions?
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
How do you find duplicate objects in an array? Using the indexOf() method. Using the has() method. Using an object & key value pairs.
With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor. If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
If your id
's are unique you can use find()
var frequencies = [{"id":124,"name":"qqq"},{"id":589,"name":"www"},{"id":45,"name":"eee"},{"id":567,"name":"rrr"}];
var result = frequencies.find(function(e) {
return e.id == 45;
});
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With