I have an array that consists of objects with two properties.
One property "value" is a number between 1 and 6. The other property "id" is a number between 1 and 200.
How can I return the "id" property of all objects with "value" = 1 and write them to a new array?
filter returns a new array containing all matching elements, [] if it matches nothing. Second thing, if you want to match 4,5 , you have to look into the string instead of making a strict comparison. To make that happen we use indexOf which is returning the position of the matching string, or -1 if it matches nothing.
function findByMatchingProperties(set, properties) { return set. filter(function (entry) { return Object. keys(properties). every(function (key) { return entry[key] === properties[key]; }); }); } var results = findByMatchingProperties(set, { color: "green" });
Today, you'll learn a useful trick to find all matching items in an array by using the Array. filter() method. The Array. filter() method creates a new array by iterating over all elements of an array and returns those that pass a certain condition as an array.
splice() JS Array Method. The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.
You should invoke the Array.prototype.filter
function there.
var filteredArray = YourArray.filter(function( obj ) { return obj.value === 1; });
.filter()
requires you to return the desired condition. It will create a new array, based on the filtered results. If you further want to operate on that filtered Array
, you could invoke more methods, like in your instance .map()
var filteredArray = YourArray.filter(function( obj ) { return obj.value === 1; }).map(function( obj ) { return obj.id; }); console.log( filteredArrays ); // a list of ids
... and somewhere in the near future, we can eventually use the Arrow functions of ES6, which makes this code even more beauty:
var filteredArray = YourArray.filter( obj => obj.value === 1 ).map( obj => obj.id );
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