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.

Javascript
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

Similar Reads

Approach 1: Using Array.filter() method

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....

Approach 2: Using Object.values()

In this approach, we will use the same array containing multiple objects which we have created previously, and here we will create another function that will be responsible for containing our logic for the above-enlightened problem statement....

Approach 3: Using the reduce() method

The reduce() method in JavaScript applies a function to each element of an array, accumulating a single result, and returns the final output....

Approach 4: Using for…of loop

The for…of loop in JavaScript iterates over iterable objects like arrays, strings, maps, sets, etc. We can use it to group objects in an array based on a common property....

Approach 5: Using forEach()

Using the forEach() method in JavaScript, we can iterate over each element in an array and group objects based on a common property....

Approach 6: Using Map

Using the Map object, we can efficiently group objects based on a common property. Map provides better performance for frequent additions and lookups compared to plain objects....

Contact Us