How to filter an array of objects in Javascript(react js & next js)
Hello there, welcome to devmaesters website, In this post I am going to show you how you can use the filter method to filter through an array of javascript objects for specific objects that passess certain condition(s).
To filter through the array for a specific object you can use the array.filter() method. The syntax for array.ilter() method looks like this
var new_array = array.filter(function(item){
return condition;
})
The item argument references the current element in the array as filter checks it against the specified condition. As the filter methods checks through the array, if an item passes the condition it gets returned to the new array.
I'll use the example below to explain further.
Lets say you have an array of objects like so:
data = [{__typename: "Currency", label: "USD", symbol: "$"},
{__typename: "Currency", label: "GBP", symbol: "£"},
{__typename: "Currency", label: "AUD", symbol: "A$"},
{__typename: "Currency", label: "JPY", symbol: "¥"},
{__typename: "Currency", label: "RUB", symbol: "₽"}
]
Consider the example question given above lets say we want the object whose label is equal to "GBP" to achieve that all we'll have to do is use the array.filter method and speficy the condition in the callback function return statement like so
const newData = data.filter(function(price){
return price.label == "GBP"
})
This assigns the value of newData to the new array that contains only the objects that passes the condition specified within the callback function.
If you "console.log" the value of "newData" you'll see that due to the condition we specified, newData contains only one object with a label of "GBP"
This method is not restricted to only one condition, you can specify as many conditions as you want just ensure to group the conditions together using javascripts logical operators. An example of an array.filter method syntax with 2 conditions is shown below:
var newArray = array.filter(function(item){
return condition1 || condition2
})
Or with the use of arrow functions
var newArray = array.filter((item) => condition1 || condition2)
What this does is to filter through the array and return the objects that pass either condition1 or condition 2.
Conclusion
You can use this method explained above to easily filter an array of dictionaries for one or more arrays that passes a specific condition in javascript. As always thanks for reading, feel free to leave any comments you have about the article down below in the comment section.