Discovering a way to retrieve objects from an array of objects with matching IDs

Here is a code snippet I put together to illustrate my objective.

arr = [
  { id:1 , name:'a', title: 'qmummbw' },
  { id:2 , name:'b', title: 'sdmus' },
  { id:2 , name:'', title: 'dvfv' },
  { id:3 , name:'c', title: 'dujuw' },
  { id:1 , name:'d', title: 'ccnyu' },
  { id:4 , name:'e', title: 'tjtjn' },
  { id:4 , name:'f', title: 'tryr' },
  { id:1 , name:'g', title: 'gbgfbgf' },
  { id:2 , name:'h', title: 'tgrtg' },
  { id:3 , name:'i', title: 'fdvd' },
  { id:1 , name:'j', title: 'dsnyc' },
  { id:1 , name:'k', title: 'nyuny' }
];

array = [];
allArray = [];
for (i = 0; i < arr.length; i++) {
  for (j = i + 1; j < arr.length; j++) {
    if (arr[i].id === arr[j].id) {
      if (!array.includes(arr[i])) {
        array.push(arr[i], arr[j]);
      } else {
        array.push(arr[j]);
      }
      allArray.push(array);

      array = []
    }

  }
}
console.log(allArray);

This is the current output:

[[{
  id: 1,
  name: "a",
  title: "qmummbw"
}, {
  id: 1,
  name: "d",
  title: "ccnyu"
}], [[circular object Object], {
  id: 1,
  name: "g",
  title: "gbgfbgf"
}], [[circular object Object], {
  id: 1,
  name: "j",
  title: "dsnyc"
}], [[circular object Object], {
  id: 1,
  name: "k",
  title: "nyuny"
}], [{
  id: 2,
  name: "b",
  title: "sdmus"
}, {
  id: 2,
  name: "",
  title: "dvfv"
}], [[circular object Object], {
  id: 2,
  name: "h",
  title: "tgrtg"
}], [[circular object Object], [circular object Object]], [{
  id: 3,
  name: "c",
  title: "dujuw"
}, {
  id: 3,
  name: "i",
  title: "fdvd"
}], [[circular object Object], [circular object Object]], [[circular object Object], [circular object Object]], [[circular object Object], [circular object Object]], [{
  id: 4,
  name: "e",
  title: "tjtjn"
}, {
  id: 4,
  name: "f",
  title: "tryr"
}], [[circular object Object], [circular object Object]], [[circular object Object], [circular object Object]], [[circular object Object], [circular object Object]]]

The aim is to group objects with the same ID together in an array, considering that the 'arr' may contain varying amounts of data.

Answer №1

If needed, you can group by the id and extract the values from the object.

const
    items = [{ id: 1 , name: 'a', title: 'qmummbw' }, { id: 2 , name: 'b', title: 'sdmus' }, { id: 2 , name: '', title: 'dvfv' }, { id: 3 , name: 'c', title: 'dujuw' }, { id: 1 , name: 'd', title: 'ccnyu' }, { id: 4 , name: 'e', title: 'tjtjn' }, { id: 4 , name: 'f', title: 'tryr' }, { id: 1 , name: 'g', title: 'gbgfbgf' }, { id: 2 , name: 'h', title: 'tgrtg' }, { id: 3 , name: 'i', title: 'fdvd' }, { id: 1 , name: 'j', title: 'dsnyc' }, { id: 1 , name: 'k', title: 'nyuny' }],
    groupedItems = items.reduce((result, obj) => ((result[obj.id] = result[obj.id] || []).push(obj), result), {});

console.log(groupedItems);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To implement filtering, you can utilize the reduce method in this manner:

const filteredData = data.reduce((accumulator, element) => {
  if (accumulator[element.id] || (accumulator[element.id] = [])) {
    accumulator[element.id].push(element);
  }
  return accumulator;
}, {});

Answer №3

let data = [
    { id:1 , name:'apple', title: 'red' },
    { id:2 , name:'banana', title: 'yellow' },
    { id:2 , name:'', title: 'green' },
    { id:3 , name:'carrot', title: 'orange' },
    { id:1 , name:'date', title: 'brown' },
    { id:4 , name:'eggplant', title: 'purple' },
    { id:4 , name:'fig', title: 'black' },
    { id:1 , name:'grape', title: 'blue' },
    { id:2 , name:'honeydew', title: 'green' },
    { id:3 , name:'kiwi', title: 'brown' },
    { id:1 , name:'lemon', title: 'yellow' },
    { id:1 , name:'mango', title: 'orange' }
  ],
    output = Object.values(data.reduce(function (result, element) {
        result[element.id] = result[element.id] || [];
        result[element.id].push(element);
        return result;
    }, Object.create(null))).map(item => item);

console.log([output]);

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

Navigating between applications

Does anyone have suggestions on setting up routing between different apps without disrupting existing code? We want to make the integration process easy when adding a new app to our main application. For example, navigating from an electronics(main app) ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

Leveraging the power of Javascript and Firebase within the Angular framework

When attempting to integrate Firebase with Angular, I encountered an issue where my localhost was not able to function properly with my JavaScript code. The strange thing is that everything works fine when the code is placed directly in the index.html file ...

Cracking the code of the @ symbol within this particular context

https://github.com/react-dnd/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js I'm trying to comprehend the significance of the @ symbol in this example. This is meant to be a straightforward drag and drop demonstration, but the implementa ...

You can submit a photo to a form as an attached file

I had a code that looked like this My goal is to simplify the process for users by allowing them to fill out additional information in a form without having to upload an image separately. I want to display the canvas image from the previous page in the fo ...

Utilize Typescript to inject types into a library

I have a code snippet that reads data from a JSON file and creates a type based on it, which is then used for further operations. import jsonData from './mydata.json' type CustomType = typeof jsonData .... This process ensures that the generate ...

Troubleshooting connectivity issues between Entities in microORM and Next.js

While trying to run my Next.js application in typescript, I encountered the following error: Error - ReferenceError: Cannot access 'Member' before initialization After consulting the documentation at https://mikro-orm.io/docs/relationships#relat ...

Converting PHP code to Typescript

Currently, I am working on developing a function for firebase that will trigger a POST request to call a specific URL. While I have successfully implemented GET requests, tackling the POST method has proven to be more challenging. I have some sample code ...

Javascript function to deselect all items

One of my functions is designed to reset all checkbox values and then trigger an AJAX request. However, there are instances when the function initiates before the checkboxes have been unchecked. function clear() { $("#a").prop("checked", false); $("#b ...

What could be causing the absence of the exported Object when importing into a different Typescript project?

I am currently in the process of developing a React component library using Typescript that I want to import into another Typescript project. Specifically, I want to import an Analytics chart library into a storybook for demonstration and testing purposes. ...

What are the best ways to make this date more visually appealing and easy to understand?

Hey there! So I have a date that looks like this: 2022-06-28T17:09:00.922108+01:00 I'm trying to make it more readable, but unfortunately, when I attempted using moment-js in my javascript/react project, it threw an error stating "invalid format". ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Is it feasible to capture a screenshot of a URL by using html2canvas?

Is it possible to take a screenshot of a specific URL using html2canvas? For example, if I have the following URLs: mydomain.com/home mydomain.com/home?id=2 mydomain.com/home/2 How can I capture and display the screenshot image on another page? window ...

Guide on utilizing Vue to trigger an API call when the input box loses focus

I am currently facing challenges while trying to learn vue, and I am not sure how to proceed. I would greatly appreciate any assistance! To begin with, I want to acknowledge that my English may not be perfect, but I will do my best to explain my issue tho ...

Deactivating AngularJS debug information in a gulp / typescript production compilation

What is the most effective approach to disabling debug data in a gulp production build? The recommended method for disabling debug data is: myApp.config(['$compileProvider', function ($compileProvider) { $compileProvider.debugInfoEnabled(false ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

When utilizing auth0, an error occurs during the grunt build process

I successfully developed a small project using AngularJS on my local machine without encountering any issues. However, when I attempted to build the project with Grunt, everything stopped working and an error occurred: vendor.ce3c01a3.js:2 Error: [$inject ...

Encountered issue with Ajax post request without any additional details provided

I could really use some assistance with this issue. It's strange, as Chrome doesn't seem to have the same problem - only Firefox does. Whenever I submit the form, Ajax creates tasks without any issues. My MySQL queries are running smoothly and I& ...

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...

Discovering the method for retrieving JavaScript output in Selenium

Whenever I need to run JavaScript code, the following script has been proven to work effectively: from selenium import webdriver driver=webdriver.Firefox() driver.get("https:example.com") driver.execute_script('isLogin()') However, when I atte ...