Sort the array by grouping it based on multiple keys of objects

What is the best strategy for grouping an array of n objects based on n keys or nested keys in the most efficient manner?

const data = [,
    {a: 1, b: 2, c:3},
    {d: 4, e: 5, f: 6},
    {a: 1, b: 2, c:3},
    {g: 7, h: 8, i: 9},
    {d: 4, e: 5, f: 6},
    {g: 7, h: 8, i: 9},
 ];

transformed to

const grouped = [
 [
    {a: 1, b: 2, c:3},
    {a: 1, b: 2, c:3},
 ],
 [
    {d: 4, e: 5, f: 6},
    {d: 4, e: 5, f: 6},
 ],
 [
    {g: 7, h: 8, i: 9},
    {g: 7, h: 8, i: 9},
 ],
]

Answer №1

const info = [
{ x: 5, y: 6, z: 7 },
{ a: 2, b: 3, c: 4 },
{ x: 5, y: 6, z: 7 },
{ d: 1, e: 2, f: 3 },
{ a: 2, b: 3, c: 4 },
{ d: 1, e: 2, f: 3 },

];

function groupItemsByKey(info) {

var groupedItems = {}

const getKeys = (item) => Object.keys(item);

const groupKey = (keys) => keys.join(",");

info.forEach(item => {
    let key = groupKey(getKeys(item));
    if (groupedItems[key])
        groupedItems[key].push(item)
    else
        groupedItems[key] = [item];
})

return Object.values(groupedItems);

}

let finalResult = groupItemsByKey(info); console.log(finalResult)

Answer №2

The concept involves:

  • utilizing a lookup table to store objects with the same identity
  • each object's identity is determined by its unique key, which in this solution is created by concatenating each pair of key-value pairs into a string
  • it is important to sort the keys alphabetically to handle scenarios like {a:1, b:2, c:3} and {b:2, a:1, c:3}, which are essentially equivalent

The worst-case time complexity for this method is O(nm) (where n represents the length of the data array, and m indicates the number of keys in an object)

Below code snippet illustrates this approach

const lookup = {}

const data = [
  { a: 1, b: 2, c: 3 },
  { b: 2, a: 1, c: 3 },
  { d: 4, e: 5, f: 6 },
  { a: 1, b: 2, c: 3 },
  { g: 7, h: 8, i: 9 },
  { d: 4, e: 5, f: 6 },
  { g: 7, h: 8, i: 9 },
]

data.forEach((obj) => {
  const uniqueKey = Object.keys(obj)
    .sort()
    .map((k) => `${k}${obj[k]}`)
    .join("-")

  if (lookup[uniqueKey] !== undefined) {
    lookup[uniqueKey].push(obj)
  } else {
    lookup[uniqueKey] = [obj]
  }
})

const res = Object.values(lookup)
console.log(res)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Redux does not have the capability to insert an object into an array

I'm currently learning about redux and I've encountered an issue trying to add multiple objects into the initialState array. I attempted using the push() method, but it isn't working as expected. The submitter value is being passed to my act ...

Why does my array of character pointers (strings) crash when I try to input data?

One of my goals is to create a program that can store an array of strings, calculate their lengths, and then re-arrange them in order from smallest to largest based on their length. I have developed an algorithm for this purpose which involves using a sw ...

Toggle the Bootstrap navbar class based on the current scroll position

I'm currently working on the development of a website that includes a feature where a static navbar transforms into a fixed navbar after scrolling down 500px. The transition from "navbar-static-top" to "navbar-fixed-top" is functioning properly. Howev ...

Select a checkbox from a dropdown menu

I need help with automatically checking a checkbox when an option is selected from a dropdown menu. Here is an example of the HTML code: <table> <tr> <td> <input type="checkbox" name="check1" />Process 1:< ...

A guide on sorting through a multi-dimensional array list in a ReactJS application

I've recently attempted to incorporate a search feature into a multi-array list. The objective is to search for specific keywords within the array, but I encountered an error during my attempts. Array for Searching: const listComponent = [{ i ...

What is the best way to convert this jQuery code into an AngularJS implementation?

I'm diving into the world of AngularJS and looking for a more elegant solution using AngularJS principles Controller $scope.filter = function($event, active, id) { var html = ""; if(active){ $http({method: 'GET& ...

jQuery is missing which is required for jquery-ui-1.9.2 and jquery-migrate-1.1.1 to function properly

Attempting to troubleshoot issues with the mobile version of my website has been quite a challenge. While I've made some progress, I have encountered four errors in the Google Chrome console that are hindering the functionality of certain links on the ...

Containers for Comparing Images are Unable to Flexibly Wrap

Check out my codepen project here: https://codepen.io/Bryandbronstein/pen/NLVQjB I've encountered a peculiar issue while experimenting with CSS and Javascript. I came across an image comparison slider on the W3C website that worked flawlessly as a si ...

Performing a function inside a JSON structure

I am dealing with a JSON object that contains a list of functions I need to access and run like regular functions. However, I'm struggling to figure out how to achieve this. Here is what I have attempted: Bootstrapper.dynamic = { "interaction": f ...

Reset the dropdown menu in React by setting a disabled option as the default selection

One issue I'm facing is trying to reset some dependent dropdowns that are controlled by react state. The functionality works fine, except when the default option is set as disabled. I came across this code snippet in a fiddle from another stackoverfl ...

Using setTime in JavaScript allows for customizing and adjusting the

I'm having trouble getting this code to display the time. I thought it would work, but it's not showing the time. Can someone please help me figure out what's going wrong? function startTime() { var currentTime = new Date(); ...

Rendering a byte array to visual representation using JavaScript

Is there a way to use JavaScript to display an image as a byte array in ASP.NET? I am looking for a solution that does not rely on any other technologies. ...

Creating a custom Shape Geometry that is derived from BoxBufferGeometry

Looking to create a ShapeGeometry that can be defined by a list of points representing the shape boundary or faces, along with a corresponding list of textures for each face. While the BoxBufferGeometry class provides a starting point, I am in need of guid ...

"Need to refresh localStorage in VueJS after navigating back with this.$router.go(-1)? Here's how

Below is my Login.vue code: mounted() { if (localStorage.login) this.$router.go(-1); }, methods: { axios.post(ApiUrl + "/login") { ... } then(response => { ... localStorage.login = true; this.$router.go(0); ...

What is the process for obtaining the eTag (MetaData) from a DocumentInfoRecord retrieval in SAP Cloud SDK using Javascript?

I am utilizing the SAP Cloud SDK for javascript to manage DocumentInfoRecords. Upon updating a DIR, I encountered error 428. Therefore, I require the etag of the request similar to what is available in the SAP Cloud API. How can I retrieve the etag from t ...

Returning a React component only under certain conditions to meet the requirements of a Suspense fallback mechanism

Whenever I return a component (using nextjs 13) that depends on fetched data, I usually conditionally render elements to ensure that the values are available: TableComponent: export const Table = ({ ...props }) => { const [tableEvents, setTableEve ...

Tips for configuring page-specific variables in Adobe DTM

Although I have integrated Adobe Analytics for tracking on my website, I am facing difficulty in properly defining the variables. This is how I attempted to define the variable: var z = new Object(); z.abc = true; z.def.ghi = true Despite following the ...

Invisible and Unrestricted automatic playback

Why is auto play muted in both Firefox and Chrome? How can we code it so that browsers don't block it? Here's the code I'm using: <audio id="audio1" src="https://notificationsounds.com/storage/sounds/file-sounds-1217-relax ...

Loop through items in Node.js

Is anyone familiar with a way to obtain the computed styles of anchor tags when hovering over them on a webpage? I've tried using this function, but it only returns the original styles of the anchor and not the hover styles. Any assistance would be gr ...

Utilizing Angular controllers to access data attribute values from child elements

Today I embarked on the journey of learning AngularJs through online tutorials. Excited about my new project, I started working on creating some useful features using Angular. Here is a snippet of my progress so far: The HTML Part <div data-ng-control ...