Grouping object properties in a new array using Java Script

I'm currently learning Java script and attempting to merge an Array of objects based on certain properties of those objects.

For instance, I have the following array which consists of objects with properties a, b, c, pet, and age. I aim to create a new array where pet and age are grouped if the properties a, b, c match for 2 objects. If any of the properties in a, b, c do not match, I want to include them as a new object in my output array.

myArray = [
  {
    a: 'animal',
    b: 'white',
    c: true,  
    pet: 'dog1',
    age: 1  
  },
  {
    a: 'animal',
    b: 'white',
    c: true,
    pet: 'dog2',
    age: 2
  },
  {
    a: 'animal2',
    b: 'white',
    c: true,
    pet: 'cat1',
    age: 5
  },
  {
    a: 'animal2',
    b: 'black',
    c: false,
    pet: 'cat2',
    age: 1
  }
]

The output array should be grouped by properties a, b, c. The first element of my output array will contain the combined values of objects 0 and 1 from the input array since they share the same properties of a, b, c. Any differing objects will be added separately.

outputArray = [
    {
        a: 'animal',
        b: 'white',
        c: true,
        pets: [{pet:'dog1,age:1},{pet:dog2,age:2}]
    },
    {
        a: 'animal2',
        b: 'white',
        c: true,
        pets: [{pet: 'cat1', age:5}]
    },
    {
        a: 'animal2',
        b: 'black',
        c: false,
        pets:[{pet: 'cat2', age: 1}]
    }
 ]

In the end, I would like an array with all elements grouped by property a, b, c. Is there a more efficient way to achieve this? I attempted using for loops but it was not successful.

Thank you in advance.

Answer №1

1) To achieve the desired outcome, you can utilize the combination of Map and for..of

const myArray = [
  {
    a: "animal",
    b: "white",
    c: true,
    pet: "dog1",
    age: 1,
  },
  {
    a: "animal",
    b: "white",
    c: true,
    pet: "dog2",
    age: 2,
  },
  {
    a: "animal2",
    b: "white",
    c: true,
    pet: "cat1",
    age: 5,
  },
  {
    a: "animal2",
    b: "black",
    c: false,
    pet: "cat2",
    age: 1,
  },
];

const dict = new Map();
for (let { a, b, c, ...rest } of myArray) {
  const key = `${a}|${b}|${c}`;
  !dict.has(key)
    ? dict.set(key, { a, b, c, pets: [{ ...rest }] })
    : dict.get(key).pets.push(rest);
}

const result = [...dict.values()];
console.log(result);
/* Ignore this part as it is not essential to the solution */
.as-console-wrapper { max-height: 100% !important; top: 0; 

2) Another approach to achieving the same outcome involves using Object.values along with reduce

const myArray = [
  {
    a: "animal",
    b: "white",
    c: true,
    pet: "dog1",
    age: 1,
  },
  {
    a: "animal",
    b: "white",
    c: true,
    pet: "dog2",
    age: 2,
  },
  {
    a: "animal2",
    b: "white",
    c: true,
    pet: "cat1",
    age: 5,
  },
  {
    a: "animal2",
    b: "black",
    c: false,
    pet: "cat2",
    age: 1,
  },
];

const result = Object.values(
  myArray.reduce((dict, { a, b, c, ...rest }) => {
    const key = `${a}|${b}|${c}`;
    !dict[key]
      ? (dict[key] = { a, b, c, pets: [{ ...rest }] })
      : dict[key].pets.push(rest);
    return dict;
  }, {})
);

console.log(result);
/* Ignore this part as it is not essential to the solution */
.as-console-wrapper { max-height: 100% !important; top: 0;

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

Steps for exporting various elements from a .vue file

In my Vue project, I am incorporating TypeScript along with Vue. There is a specific scenario where I need to export multiple items from my .vue file. Here's an example of what I want to achieve: // FooBar.vue <template> ... </template& ...

Exploring MongoDB with Array Values

I am working with a user schema. { phone:'String' } Within my query field, I have an array of phone numbers like ['1233','2134','43433'] that I need to search for. My goal is to check if these phone numbers exist ...

What is the best way to populate a 2D array with random characters in C++ by leveraging classes?

I'm currently working on a Word Search Puzzle project for school, and I'm encountering a specific issue. The challenge lies in populating a 2D array with random characters. While this task is not overly difficult, things become confusing when cl ...

Is there a solution to resolving the type error that I am unable to identify?

I am attempting to implement a custom cursor feature in Vue 3, but unfortunately my code is not functioning as expected. Below you can find the code snippet I have been working on: <template> <div id="cursor" :style="cursorPoi ...

Displaying various Vue components within Laravel 6.x

After diving into Laravel and Vue, I managed to put together a navigation component as well as an article component. The problem I'm facing is that although my navigation vue component is visible, the article component seems to be missing. Reviewing ...

Looping through an array of JSON objects without keys in Java for an Android application

I am looking to loop through a JSON array containing objects, but all the tutorials I've found are for keyed JSON objects. This is how the JSON array appears: items:[{i know}, {what you did} ,{last summer}] ...

Employing condition-based require() statements in JavaScript

I am currently experimenting with conditionally loading modules that are Vue components. Review the code snippet below for a better understanding: index.js My goal is to dynamically load different components based on the window URL (since I cannot use vu ...

I'm having trouble with my dropdown navigation menus - they keep popping back up and I can't seem to access

My website is currently in development and can be accessed at: The top navigation bar on the homepage functions properly across all browsers. However, there are three sections with dropdown submenus - About Us, Training, and Careers. These dropdown submen ...

What is the behavior of a variable when it is assigned an object?

When using the post method, the application retrieves an object from the HTML form as shown below: code : app.post("/foo", (req, res)=> { const data = req.body; const itemId = req.body.id; console.log(data); console.log(itemId); }) ...

Tracking and managing user clicks on external links within a vue.js application

I am currently working on a web application that retrieves data from a CMS. Utilizing the Vue-Router in 'history' mode, I need to address content fetched from the API which may include links. My goal is to manage specific links using the router w ...

What is the purpose of wrapping my EventEmitter's on function when I pass/expose it?

My software interacts with various devices using different methods like serial (such as USB CDC / Virtual COM port) and TCP (like telnet). To simplify the process, I have created a higher-level interface to abstract this functionality. This way, other sect ...

Exploring Unanchored Substring Queries in Loopback API

Searching for a solution to implement a basic substring query using the loopback API for a typeahead field. Despite my efforts, I have not been able to find a clear answer. I simply want to input a substring and retrieve all brands that contain that subst ...

Is there a convenient method to populate a 2D array once it has been initialized?

In my program, I am using a 2D array to store the coordinates of a cube. The array is initialized at the beginning and easily filled with the desired values like this: float cubeRef[3][8] = { { -1, 1, 1, -1, -1, 1, 1, -1 }, { 1, 1, ...

The useEffect function is executing two times

Check out this code snippet: import { type AppType } from 'next/app' import { api } from '~/utils/api' import '~/styles/globals.css' import Nav from '~/components/Nav' import { useEffect, useState } from 'react& ...

JavaScript: The hyperlink provided in the data-href attribute is not functioning properly within the carousel

I have a carousel with images that I want to link to specific pages: JS Fiddle. My goal is to have each image in the carousel direct users to a different webpage when clicked. For example: Clicking on the wagon image should go to wagon.com Clicking on th ...

Using Modal Functions in AngularJS Controller

I have been working on a project that utilizes the ui.bootstrap. As per the instructions from the tutorial I followed, my setup looks something like this: 'use strict'; angular.module('academiaUnitateApp') .controller('EntryCtr ...

The jQuery dropdown selection for only displaying the month and year is not functioning properly when using the select

Currently, I am utilizing a datepicker with only the month and year as options to select from using dropdowns. However, when I apply the following CSS to disable the days of the datepicker, it ends up affecting all datepickers in my JSP file. 1. Is there ...

There is no record of the property's history

I am embarking on a fresh project utilizing React and TypeScript. One of the hurdles I have encountered is with the Router. Strangely, TypeScript does not recognize the history property, even though it should be accessible as mentioned in the documentation ...

Determine in jQuery whether a Value is present within a JSON dataset

[ { "link" : "images/examples/image-3.png", "image" : "images/examples/image-3.png", "title" : "copy" }, { "link" : "images/examples/image-3.png", "video" : "video placeholder", "title" : "c ...

A guide on how to examine the array index within a nested array

Let's consider this scenario with arrays: numbers = [[3,5],[2,4]] elements = [2,4] It seems like the array numbers contains the array elements But when we try to find the index of elements in numbers, it returns -1 Any thoughts on how to tackle th ...