Filtering out duplicate names from an array of objects and then grouping them with separator IDs can be achieved using JavaScript

Imagine we have an array

[
{id: 1, label: "Apple"},
{id: 2, label: "Orange"},
{id: 3, label: "Apple"},
{id: 4, label: "Banana"},
{id: 5, label: "Apple"}
]

We want the output to be like this

[
{id: 1~3~5, label: "Apple"},
{id: 2, label: "Orange"},
{id: 4, label: "Banana"}
]

Can you help provide a solution using JavaScript?

Answer №1

If you're looking to manipulate arrays in JavaScript, you can utilize the Array.reduce method:

const arr = [
  {id: 1, label: "Hello"},
  {id: 2, label: "World"},
  {id: 3, label: "Hello"},
  {id: 4, label: "Sunshine"},
  {id: 5, label: "Hello"}
]

const res = arr.reduce((a, itm) => {
  var f = a.filter(e => e.label == itm.label);
  f.length > 0 ? f[0].id += "~" + itm.id : a.push(itm)
  return a;
}, [])
console.log(res)

Answer №2

How do we solve this problem?

const newArray = [
  { id: 1, name: "Apple" },
  { id: 2, name: "Banana" },
  { id: 3, name: "Apple" },
  { id: 4, name: "Orange" },
  { id: 5, name: "Apple" },
];

// Function to remove duplicates based on a key
const removeDuplicates = (array, key) => {
  const values = new Set();
  return array.filter((item) => {
    const value = item[key];
    if (values.has(value)) {
      return false;
    }
    values.add(value);
    return true;
  });
};

// The new filtered array
const resultArray = removeDuplicates(newArray, "name");

console.log(resultArray);

Answer №3

My preferred method involves utilizing Array.prototype.reduce in combination with a Set.

Here is an example:

const itemsArray = [
  { id: 1, name: "Apple" },
  { id: 2, name: "Banana" },
  { id: 3, name: "Apple" },
  { id: 4, name: "Orange" },
  { id: 5, name: "Apple" },
];

// Remove duplicates based on 'name' property.
const uniqueNameSet = new Set(itemsArray.map(item => item.name));

const resultArray = Array.from(uniqueNameSet).map((uniqueName) => {
  return {
    name: uniqueName,
    ids: itemsArray
      .filter((item) => item.name === uniqueName)
      .reduce((ids, item) => {
        return ids ? ids += `~${item.id}` : item.id;
      }, '')
  }
});

console.log(resultArray)

Answer №4

It would be incredibly helpful to have a versatile groupBy function to streamline processes.

function groupBy(collection, fn) {
  const groups = new Map();
  for (const item of collection) {
    const key = fn(item);
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(item);
  }
  return groups;
}

The groupBy utility mentioned above can be applied to transform your data effectively.

const transformedData = Array.from(groupBy(data, item => item.category))
  .map(([category, items]) => ({ id: items.map(item => item.id), category }));

This process rearranges your data as follows.

// group the items based on category
let transformedData = groupBy(data, item => item.category);
//=> { 
//   "Tech": [
//     {id: 1, category: "Tech"},
//     {id: 3, category: "Tech"},
//     {id: 5, category: "Tech"}
//   ],
//   "Fashion": [
//     {id: 2, category: "Fashion"}
//   ],
//   "Food": [
//     {id: 4, category: "Food"}
//   ]
// }

// convert the Map instance into an Array to utilize .map()
transformedData = Array.from(transformedData);
//=> [
//   ["Tech", [
//     {id: 1, category: "Tech"},
//     {id: 3, category: "Tech"},
//     {id: 5, category: "Tech"}
//   ]],
//   ["Fashion", [
//     {id: 2, category: "Fashion"}
//   ]],
//   ["Food", [
//     {id: 4, category: "Food"}
//   ]]
// ]

// adjust the array into the desired format using .map()
transformedData = transformedData.map(([category, items]) => ({ id: items.map(item => item.id), category }));
//=> [
//   { id: [1,3,5], category: "Tech" },
//   { id: [2], category: "Fashion" },
//   { id: [4], category: "Food" },
// ]

If you prefer the format 1~3~5, change:

items.map(item => item.id)
// to
items.map(item => item.id).join("~")

const data = [
  {id: 1, category: "Tech"},
  {id: 2, category: "Fashion"},
  {id: 3, category: "Tech"},
  {id: 4, category: "Food"},
  {id: 5, category: "Tech"}
];

const transformedData = Array.from(groupBy(data, item => item.category))
  .map(([category, items]) => ({ id: items.map(item => item.id), category }));

console.log(transformedData);


function groupBy(collection, fn) {
  const groups = new Map();
  for (const item of collection) {
    const key = fn(item);
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(item);
  }
  return groups;
}

References:

Answer №5

var elements = [{
    id: 1,
    label: "Apple"
  },
  {
    id: 2,
    label: "Banana"
  },
  {
    id: 3,
    label: "Apple"
  },
  {
    id: 4,
    label: "Orange"
  },
  {
    id: 5,
    label: "Apple"
  }
];

//Declare necessary variables
var uniqueElements = [];
var currentElement = null;
var flags = [], uniqueLabelArr = [];

//Get Unique label values array
for (var i = 0; i < elements.length; i++) {
  if (flags[elements[i].label]) continue;
  flags[elements[i].label] = true;
  uniqueLabelArr.push(elements[i].label);
}

// Iterate the input array for all unique elements
for (var i = 0; i < uniqueLabelArr.length; i++) {
  currentElement = uniqueLabelArr[i];
  var mergedId = '';
  for (var j = 0; j < elements.length; j++) {
    if (elements[j].label == currentElement) {
        if(mergedId == '')
        mergedId = elements[j].id;
      else
        mergedId = mergedId + '~' + elements[j].id;
    }
  }
  //Push the result object to final array
  uniqueElements.push({
    id: mergedId,
    label: currentElement
  });
}
console.log(uniqueElements);

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

Trouble with JavaScript preventing the opening of a new webpage

I need help with a JavaScript function to navigate to a different page once the submit button is clicked. I have tried using the location.href method in my code, but it's not working as expected. Even though I am getting the alert messages, the page i ...

Is it secure to attach the password field to a data object property in Vue.js?

This particular inquiry has been bothering me lately. Imagine I aim to create a login element for my application (using Vue), containing 2 specific input fields - one for the userID and the other for the password. The focus here is on the security of the ...

Error: The function $(...)button is not recognized

I encountered the error Uncaught TypeError: $(...).button is not a function when trying to add a product. I have checked and confirmed that the button is visible on the root, but the error persists. This issue only occurs on one specific page in Opencart ...

Unable to see the array values in jquery autocomplete

Hey there, I'm currently using jQuery autocomplete with CodeIgniter. My result array is fetched from the database and I am sending it back as JSON-encoded data. However, I am facing an issue where the values in the search results are not being display ...

Tips for duplicating a collada model in three.js?

I've imported a .dae model into my scene and I want to use it multiple times. The code provided works with meshes, but the collada.scene object is not a mesh: var mesh2 = new THREE.Mesh( loadedMesh.geometry, loadedMesh.material ); Is there a way to ...

NextJS struggles to load EditorJS plugins

I am currently working on integrating EditorJS into my NextJS project. The editor is loading properly without any plugins, with only paragraph as a block option. However, I'm facing an issue when trying to add plugins using the tools prop which result ...

Preventing page refresh with Javascript when clicking on CAPTCHA

I have been exploring a CAPTCHA tutorial on TutsPlus.com and I am facing an issue where the 'Incorrect Captcha message' keeps appearing, indicating that my user input through $_POST does not match the stored $_SESSION string. Upon investigating ...

Extract data from arrays within other arrays

I have an array called societies: List<Society> societies = new ArrayList<>(); This array contains the following information: [{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes‌​1"}, {"society_id":2,"name":" ...

How can I capture a screenshot of the div displaying pictures uploaded by the user on the frontend?

Take a look at this code snippet. It allows users to upload images, move them around, resize, and rotate them once uploaded. $(function() { var inputLocalFont = $("#user_file"); inputLocalFont.change(previewImages); function previewImages() { ...

What is the best way to eliminate the ' from every element in an array in this situation?

My form has hidden fields with values enclosed in single quotes like 'enable'. Using jQuery, I extract these values and push them into an array. This array is then sent to a PHP file using JavaScript through the url attribute of the jQuery AJAX m ...

Increasing a value within HTML using TypeScript in Angular

I'm working with Angular and I have a TypeScript variable initialized to 0. However, when trying to increment it using *ngFor in my .ts file, the increment is not happening (even though the loop is running correctly). my-page.html <div *ngFor=&quo ...

Error: The requested collection# cannot be found in the Node.js Express routing system

Recently, I have started learning nodejs and implemented a simple API that allows users to log in with passport and then redirects them to the /collections route. While this part is functioning correctly, I am encountering issues with POST requests which a ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Tips on obtaining checkbox value in an AJAX request

I need to retrieve the value of a checkbox using Ajax in order to store it as a user preference in the database. This task is new to me, and I'm feeling a bit overwhelmed. Here is my JavaScript file: $(document).ready(function() { E.accounts.chang ...

Converting DateTime to text in PHP

I'm facing a challenge where I need to separate my datetime value (stored in database) using PHP. $temps[0]['Date_deb']; // --> "2017-10-07 00:00:00" $letemps = $temps[0]['Date_deb']; //echo $letemps->format(&a ...

Rearrange the elements of an array in a way that prevents consecutive repetitions

My challenge involves an array of repeating letters: AABCCD I want to rearrange them into a pseudo-random order while adhering to a specific restriction. To do this, I considered using the Fisher-Yates method. However, my requirement is that there shou ...

Iterate through an HTML table and transfer matching items along with their corresponding calculated amounts to a separate table

<html> <body> <div> <table border="1" id="topTable"> <thead> <th>Item</th> <th>Sold</th> </thead> <tbody id="topTableBody"> <tr> ...

Tips for successfully including special characters in a query string using asp.net and jquery

Is there a way to pass %20 in the Query string without it being interpreted as a space in the code behind? I need to pass query strings using ASP.NET and also from JavaScript. Any suggestions on how to achieve this? Thank you in advance for your help. ...

Angular - Issue with setting default value in a reusable FormGroup select component

My Angular reusable select component allows for the input of formControlName. This input is then used to render the select component, and the options are passed as child components and rendered inside <ng-content>. select.component.ts import {Compon ...

Recursively apply a custom condition to filter a tree

Within this tree structure, I need to extract items with a release version of 0.0.1 to use in building my navigation based on that specific release number. { title: '', items: [ { title: '', path: '', ...