Skip to content

Groups JavaScript objects array by a key and returns grouped array.

License

Notifications You must be signed in to change notification settings

grjan7/group-objects-array

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

group-objects-array

NPM version NPM downloads Known Vulnerabilities

Description

Groups JavaScript objects array by a key and returns grouped array.

Groups the scattered objects in an array based on a groupByKey (e.g. id). For the given groupByKey value, if there is a multiple occurrence of same key (e.g., contact key for id: 3) but with unique values, then the values will be grouped into an array.

Installation

  npm i group-objects-array

Usage

groupObjectArrayByKey(objArr, groupByKey)

  • objArr an array of objects to be grouped
  • groupByKey an object key to group the objects
 const { groupObjectArrayByKey } = require('group-objects-array');
 
 const objArray = [
   { id: 1, name: "John" },
   { id: 2, name: "Aaron" },
   { id: 1, age: 20 },
   { id: 2, age: 30 },
   { id: 3, name: "Michel" },
   { id: 1, address: { street: "123 Main Street", city: "NY", country: "USA" } },
   { id: 3, contact: "+01-51245 53125" },
   { id: 3, contact: "+02-51245 53125" },
   { id: 1, address: { street: "123 Main Street", city: "NY", country: "USA" } }  
 ];
  
 groupObjectArrayByKey(objArray, "id");
 

returns

[
  {
    id: 1, 
    name: "John", 
    age: 20, 
    address: { street: "123 Main Street", city: "NY", country: "USA" }
  },
  {
    id: 2,
    name: "Aaron",
    age: 30
  },
  {
    id: 3,
    name: "Michel",
    contact: [ "+01-51245 53125", "+02-51245 53125" ]
  } 
]

uniqueArray(arr)

This function returns an array with duplicates removed.

  • arr an array to be deduplicated to have only unique values
const { uniqueArray } = require("group-objects-array");

const arr = [
  { name: "John", age: 30 },
  { name: "Doe", age: 29 },
  { name: "John", age: 30 },
  { name: "Michel", age: 21 }
];

uniqueArray(arr);

returns

[
  { name: "John", age: 30 },
  { name: "Doe", age: 29 },
  { name: "Michel", age: 21 }
]

isItemInArray(arr, item)

This function checks if an item is in the given array.

  • arr source array
  • item item to be checked whether it is in the array
const { isItemInArray } = require("group-objects-array");

const arr = [ { name: "John" }, "world" ];

isItemInArray(arr, { name: "John" }); // returns true

Releases

No releases published

Packages

No packages published