Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Object.groupBy()

ES2024 introduced the Object.groupBy() method in JavaScript.

This method groups the elements of an object based on string values returned by a callback function.

Object.groupBy() does not modify the original object.

Example

// Create an Array
const fruits = [
  {name:“apples”, quantity:300},
  {name:“bananas”, quantity:500},
  {name:“oranges”, quantity:200},
  {name:“kiwi”, quantity:150}
];

// Callback function to Group Elements
function myCallback({ quantity }) {
  return quantity > 200 ? “ok” : “low”;
}

// Group by Quantity
const result = Object.groupBy(fruits, myCallback);

Browser Support

Object.groupBy() is a feature introduced in ES2024.

It has been supported in new browsers since March 2024.

js 19

Object.groupBy() vs Map.groupBy()

The difference between Object.groupBy() and Map.groupBy() is:

Object.groupBy() groups elements into a JavaScript object.

Map.groupBy() groups elements into a Map object.

JavaScript Object.keys()

The Object.keys() method returns an array containing the keys of an object.

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50,
  eyeColor: “blue”
};

// Get the Keys
const keys = Object.keys(person);

JavaScript for…in Loop

The JavaScript for…in statement iterates over the properties of an object.

Syntax

for (let variable in object) {
  // code to be executed
}

The code inside the for…in loop is executed once for each property.

It iterates through the properties of an object.

Example

const person = {
  fname:” John”,
  lname:” Doe”,
  age: 25
};

for (let x in person) {
  txt += person[x];
}