How to extract various arrays of identical objects from a larger array in JavaScript

I am working with an array containing objects of this structure:

{id: 543, firstName: 'Ted', lastName: 'Foo', age: 32}

My goal is to filter out objects in the array that have the same values for both the firstName and age properties. The desired outcome is having multiple arrays where elements share the same values for age AND firstName. For example:

[{id: 543, firstName: 'Ted', lastName: 'Foo', age: 32},
{id: 123, firstName: 'Ted', lastName: 'Bar', age: 32},
{id: 432, firstName: 'Ted', lastName: 'Baz', age: 32}]

[{id: 989, firstName: 'George', lastName: 'Smith', age: 67},
{id: 876, firstName: 'George', lastName: 'Miller', age: 67},
{id: 334, firstName: 'George', lastName: 'Stone', age: 67}]

How would you approach this problem elegantly? (ES6 solutions are welcome)

Answer №1

To get an array of arrays, you can utilize the reduce() and Object.values() methods.

const data = [
  {id: 543, firstName: 'Ted', lastName: 'Foo', age: 32},
  {id: 123, firstName: 'Ted', lastName: 'Bar', age: 32},
  {id: 432, firstName: 'Ted', lastName: 'Baz', age: 32},
  {id: 989, firstName: 'George', lastName: 'Smith', age: 67},
  {id: 876, firstName: 'George', lastName: 'Miller', age: 67},
  {id: 334, firstName: 'George', lastName: 'Stone', age: 67}
]

const result = Object.values(data.reduce(function(r, e) {
  const key = `${e.firstName}|${e.age}`;
  if(!r[key]) r[key] = [e];
  else r[key].push(e)
  return r;
}, {}))

console.log(result)

Answer №2

To organize them, I would group the elements by their attributes using nested objects. (Instead of concatenating keys for a flat object, I prefer to maintain separate entities.)

Once grouped, I would then consolidate them into a single array.

var information = [
  {id: 543, firstName: 'Ted', lastName: 'Foo', age: 32},
  {id: 123, firstName: 'Ted', lastName: 'Bar', age: 32},
  {id: 432, firstName: 'Ted', lastName: 'Baz', age: 32},
  {id: 989, firstName: 'George', lastName: 'Smith', age: 67},
  {id: 876, firstName: 'George', lastName: 'Miller', age: 67},
  {id: 334, firstName: 'George', lastName: 'Stone', age: 67}
]

function unify(obj, flat) {
   return Object.keys(obj).reduce((arr, key) => arr.concat(!Array.isArray(obj[key]) ? unify(obj[key]): [obj[key]]), [])
}

function categorizeBy(keys, arr) {
   return arr.reduce(function(grouped, item) {
        let node, value;
        for (var i = 0; i < keys.length; i++) {
            value = item[keys[i]]
            if (i == keys.length - 1) node[value] = node[value] || []
            else node = node && (node[value] = node[value] || {}) || (grouped[value] = grouped[value] || {})
        }

        node[value].push(item);
        return grouped;
   }, {})
}

console.log(unify(categorizeBy(["firstName", "age"], information)))

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

What could be the reason behind Cesium viewer's failure to show a model after I upload it?

My application features a 3D map of a city with an "Add building" button. Upon clicking this button, a model of a building should be inserted into the map. However, all I see is a selection marker at the intended location without the actual building appea ...

Discovering duplicate values in an existing array and storing them in a new array in AngularJS can be achieved by iterating through the

/Here is my JSON data./ $scope.fund = [ { id: 1, fundname: 'HDFC Medium Term Opportunities-G', date: '12/05/2016', amountunits: '11120', price: '200&apo ...

Choose the span element within every other td that is not enclosed by an anchor tag

The table structure I am working with is as follows: <tr> <td> <a> <span> some content </span> </a> </td> <!-- td having straight span --> <td> <span> ...

Retrieve the quantity information from a JSON object

Hello everyone! I am new to programming and need help. How can I retrieve the 'qty' value of 0 using JSON and PHP from the following data: {"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":0,"raw":0}]} I have attempted the following code: ...

What is the best way to protect old documents when selecting new files in a multi-file uploader?

I created a file upload feature with file previews using HTML5 and the file reader, which is functioning well. However, I'm facing an issue where old files selected by the user get removed from the input file field if a new file is selected in a singl ...

Searching for multiple values using ng-model in AngularJS is a powerful feature that allows

I've looked everywhere for a solution to my problem but I haven't found an exact match. Can anyone lend a hand? Here's the ng-repeat filter list I'm working with: <ul> <li ng-repeat="f in filterOptions"> <p>{{f ...

Why is my "npm install" pulling in unnecessary libraries that I didn't even mention?

I've listed my dependencies in package.json as follows: { "cookie-parser": "~1.0.1", "body-parser": "~1.0.0", "express": "~3.5.0", "socket.io":"1.0", "mongodb":"2.2.21", "request":"2.79.0", "q":"1.4.1", "bcryptjs":"2.4.0", "jsonw ...

Change the color of the background in the Material UI Snackbar

Whenever I try to change the background color of the Snackbar by setting a className, it doesn't get applied properly. Instead, for a brief moment when the page renders, the desired background color appears and then quickly gets replaced. I've g ...

Transition not influencing the scale property when activating a class

My modal is not scaling in and out properly when I toggle the 'active' class. It either fully scales out or scales in without any transition. Example: const openPopupButtons = document.querySelectorAll('[data-popup-target]'); const ...

Executing a get request in Backbone without using the Option parameter by implementing the beforeSend method

After gathering insights from the responses to this and this queries, I have formulated the code below for a GET request: var setHeader = function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa($rootScope.login.Gebruikersnaam + ":" + $r ...

Tips for updating the content of a div with the click of another div

Is there a way to dynamically change the content of a div upon clicking on a menu item? Here is the current layout for reference: https://i.stack.imgur.com/nOnlQ.png Below is the CSS and HTML code snippet: body { background-color: #555657; ...

A step-by-step guide on how to use ajax/jquery to access an external webpage without relying on iframe

Is there a more effective way to call another page, such as http://www.google.com, and load it into my specific div without using an iframe? I attempted to do so with ajax... $.ajax({ url : 'http://www.google.com', success : function ( ...

How to encase HTML content within a scope variable without relying on ng-bind-html

Is there a way to include HTML content using a scope variable in AngularJS without utilizing ng-bind-html-unsafe? <div ng-controller="dataController">{{test}}</div> $scope.test = "<div>Html content</div>" ...

Utilizing a library across various files in Node.js

I am looking to integrate Winston for logging in my nodejs express project. Within my main file ( server.js ) I currently have the following code snippet: const winston = require('winston'); winston.level = process.env.LOG_LEVEL winston.log(&ap ...

Tracing a path with a snapping motion using my thumb

Before we begin, let's take a look at the example below. The functionality of this component should mimic that of an input type range. However, I am facing some challenges in calculating the step value and snapping the thumb onto the trail based on t ...

Utilizing useEffect in the header component of ReactJS/Next.js: A Comprehensive Guide

In my next.js/react project, I have a component called header.js that is included on every page. Within this component, I've implemented a typewriter effect with rotation by using the following code snippet inside useEffect: export default function H ...

Tips for developing a versatile code for passport.authenticate

I have a scenario where multiple controllers contain various methods that require user authentication to access database data. I am currently attempting to streamline the authentication process to avoid repetition in my code. Within the controller: const ...

Angular directive for automatically selecting a <select> value when there is only one option available in ngOptions

How can I create a directive that automatically preselects an option if only one item is available in the ngOptions scope? Currently, my code looks like this: <select id="provider" name="provider" class="form-control" ng-model="foo.provider" ...

Working with promises and Async/Await in Express/node can sometimes feel ineffective

Currently, I am delving into the world of node and express with the aim to create a function that can extract data from a CSV file uploaded by the user. My challenge lies in the fact that the data is being outputted as an empty array before it goes through ...

Examining Angular Modules using Jasmine Unit Tests

Currently, I am integrating an AngularJS service into my application. Upon testing, I discovered that the service is not as reliable as I had hoped. To address this issue, I decided to implement some unit tests for it. While the service functions properly ...