How to useArray.filter() method in Javascript
In this approach, we will create an array having multiple objects in itself and then use Array.filter() method we will filter out certain values from that complete array of objects.
Syntax:
array.filter(callback(element, index, arr), thisValue);
Example: in this example, we are using the above-explained approach.
let fruits = [
{
fruit_name: "Apple",
fruit_color: "Red",
},
{
fruit_name: "Pomegranate",
fruit_color: "Red",
},
{
fruit_name: "Grapes",
fruit_color: "Green",
},
{
fruit_name: "Kiwi",
fruit_color: "Green",
},
];
let filtered_fruits = fruits.filter((fruit) =>
fruit.fruit_color === "Red");
console.log(filtered_fruits);
Output
[ { fruit_name: 'Apple', fruit_color: 'Red' }, { fruit_name: 'Pomegranate', fruit_color: 'Red' } ]
How to group objects in an array based on a common property into an array of arrays in JavaScript ?
In this article, we will try to understand how we may easily group objects in an array based on a common property into an array of arrays in JavaScript with the help of an example itself. Grouping objects in an array based on a common property into an array of arrays in JavaScript. Organize data by shared property for efficient data manipulation.
Several methods can be used to group objects in an array based on a common property:
Table of Content
- Approach 1: Using Array.filter() method
- Approach 2: Using Object.values()
- Approach 3: Using the reduce() method
- Approach 4: Using for…of loop
- Approach 5: Using forEach()
- Approach 6: Using Map