Remove duplicate values from an array by applying a specific condition

I am encountering an issue with an array that contains duplicate elements

let myArray=[
     {role: "role-1", deviceId: ""},
     {role: "role-2", deviceId: "d-2"},
     {role: "role-3", deviceId: "d-3"},
     {role: "role-1", deviceId: "d-1"},
     {role: "role-2", deviceId: ""},
     {role: "role-4", deviceId: ""}
     {role: "role-5", deviceId: ""}
]

My goal is to eliminate the duplicate roles from the array, keeping only one role for each distinct role-value pair where the deviceId is not empty(""), and retain only one duplicate if the deviceId is empty in this manner.

myArray=[
         {role: "role-1", deviceId: "d-1"},
         {role: "role-2", deviceId: "d-2"},
         {role: "role-3", deviceId: "d-3"}
         {role: "role-4", deviceId: ""}
         {role: "role-5", deviceId: ""}

 ]

The function I have written attempts to solve this issue:

function dedupeByKey(arr, key) {
  const temp = arr.map(el => el[key]);
  return arr.filter((el, i) =>
    temp.indexOf(el[key]) === i
  );
}

console.log(dedupeByKey(myArray, 'role'));

However, the current implementation does not prioritize deviceIds with values, resulting in roles with empty(deviceId) being included. How can I address this issue?

Answer №1

To easily handle objects in JavaScript, you can utilize the reduce method with a default object and then convert it to an array if needed.

let myArray = [
     {role: "role-1", deviceId: ""},
     {role: "role-2", deviceId: "d-2"},
     {role: "role-3", deviceId: "d-3"},
     {role: "role-1", deviceId: "d-1"},
     {role: "role-2", deviceId: ""},
     {role: "role-4", deviceId: ""},
     {role: "role-5", deviceId: ""}
]

const result = myArray.reduce((accumulator, currentItem) => {
  if (accumulator[currentItem.role]) return accumulator // skip iteration if deviceId already exists
  accumulator[currentItem.role] = currentItem.deviceId // add deviceId if it does not exist
  return accumulator
}, {})

let finalArray = Object.keys(result).map(key => { return { role: key, deviceId: result[key] }})

console.log(finalArray)

Answer №2

To transform a unique role to an object and condense it into an array, utilize the code snippet below:

let myArray = [
     {role: "role-1", deviceId: ""},
     {role: "role-2", deviceId: "d-2"},
     {role: "role-3", deviceId: "d-3"},
     {role: "role-1", deviceId: "d-1"},
     {role: "role-2", deviceId: ""},
     {role: "role-4", deviceId: ""},
     {role: "role-5", deviceId: ""}
];

var uniqueObj = myArray.reduce(function(acc, item) {
  var deviceId = acc[item.role] && acc[item.role].deviceId || item.deviceId;
  acc[item.role] = item;
  acc[item.role].deviceId = deviceId;
  return acc;
}, {});

var result = Object.keys(uniqueObj).reduce(function(acc2, item) {
  acc2.push(uniqueObj[item]);
  return acc2;
}, []);

console.log(result);

Answer №3

One approach is to use a filter function and search ahead in the array for duplicates to determine whether to keep or remove the index.

const myArray= [
     {role: "role-1", deviceId: ""},
     {role: "role-2", deviceId: ""},
     {role: "role-3", deviceId: "d-3"},
     {role: "role-1", deviceId: "d-1"},
     {role: "role-2", deviceId: ""},
     {role: "role-4", deviceId: ""},
     {role: "role-5", deviceId: ""}
]
  
const cleanArray = myArray.filter( (item,index,array) => {
  if ( item.deviceId === "") {
    // Filter out items with duplicate roles found later in the array
    return !array.some((i,idx) => i.role === item.role && idx > index )
  }
  return true 
})

// Sort the cleaned array for presentation
const sortedArray = cleanArray.sort( (curr, next) => curr.role >  next.role? 1:-1);

console.log(sortedArray)

Answer №4

To efficiently organize the data by `role` and then select the first one with a corresponding `deviceId`, you can utilize the following code snippet:

  function groupBy(array, key) {
    const result = { };
    for(const el of array) {
      if(!result[ el[key] ]) result[ el[key] ] = [];
       result[ el[key] ].push(el);
   }
  return result;
}

const resultArray = [];
const groupedData = groupBy(myArray, "role");
for(const group of Object.values(groupedData)) {
  resultArray.push(group.find(item => item.deviceId) || group[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

Utilizing npm packages from third-party sources within a custom extension for personal use (not intended for distribution)

Exploring the idea of developing a basic Firefox extension that involves external modules such as Firebase and Cheerio, but there doesn't seem to be much information available on this topic. I noticed there are legacy options like jpm, but they'r ...

Finding out whether the current date falls between a startDate and endDate within a nested object in mongoose can be done by using a specific method

My data structure includes a nested object as shown: votingPeriod: {startDate: ISOdate(), endDate: ISOdate()}. Despite using the query below, I am getting an empty object back from my MongoDB. const organizations = await this.organizationRepository.find( ...

Remove numerous entries from the WordPress database by selecting multiple checkboxes

A new customer table named "tblvessel" has been created in the Wordpress database. The code provided below selects records from the database and displays them as a table with checkboxes next to each record, assigning the record's 'ID' to the ...

Hide Navbar when clicking on menu item

I'm struggling with finding a solution to this issue, as I am unsure of how to proceed. The problem I am facing is that when I click on an item, the router-view changes correctly, but the menu remains open. I would like it to close after a click. ...

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

Tips for integrating an arrow function as a property in a functional programming approach using JavaScript or TypeScript

Suppose I were to create a constructor for a functional class with TypeA as an argument, and TypeB representing the type of the class itself. In such cases, I can implement it using: functionName(argument: TypeA): TypeB { this.property = argument; ...

My changes to the HTML file are not being reflected in the browser, even after clearing the cache. This is happening in an Angular and Node.js application

I'm currently developing an application using Angular and Node.js. I've noticed that when I make changes to the HTML file, the browser isn't updating even after clearing the cache. Could this be a coding issue? Any suggestions on how to fix ...

While loop not yielding immediate result with asynchronous function

As a beginner in Node.js, I have successfully connected an LCD Panel and a 4x4 Membrane matrix keypad to my Raspberry Pi. Using Node.js, I have programmed them to work together. My goal is to have the LCD panel immediately display any key pressed on the ke ...

Properly executing a for loop

I have devised a method to transform Swagger 1 documentation into Swagger 2. This involves utilizing an array of resources as input for the conversion process. However, I have encountered an issue where the code seems to be skipping ahead and jumping to ...

RegEx not triggering Mongoose hooks

When performing queries on my mongo collections, I am attempting to call specific hooks for them. DispatchRequest.findOneAndUpdate({user_name:"umesh"},{email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdac8 ...

Tips for utilizing nested filters to identify when there is a single list item and its child is specifically a <strong> tag

I am seeking to designate a specific class to the <ul> element only under certain conditions: it must have a single <li> which contains a solitary child, namely <strong>, without any additional text nodes or elements preceding or followin ...

Tips for accessing a value in a multidimensional json array without the key in JavaScript/jQuery?

I'm working with a JSON file that contains a multidimensional array. The array consists of city data at the first level and temperature data at the second level. I'm facing difficulties in dynamically extracting values from the second level. I a ...

A collection nested inside another collection

In my quest to create a program for tracking a baseball card collection, I came up with the idea of simulating buying packs of 7 cards in order to complete a total collection of 500 unique cards. Each card is assigned a value between 0 and 499, and I dev ...

Is it possible to bypass the standard syntax and manipulate geometry buffers directly in three.js in order to achieve improved performance?

Embarking on a creative journey into the realm of geometry generation and manipulation, I am eager to explore intricate and large-scale projects. While I am familiar with the conventional methods of achieving this, as demonstrated in the informative respon ...

Leveraging jQuery and Ajax for extracting and transmitting parameters within href links

Here is my HTML link code: <div id="message"></div> <a href="cats.php?id=60&color=brown&name=kitty" id="petlink"> Click here </a> I want to use jQuery and Ajax to send these parameters when the link is clicked: id=60 colo ...

Utilizing a custom handler for Jquery Oembed functionality

I always preferred using my own function instead of using $(document).ready() to dynamically load an embed from a URL. This is what I have tried: function insertVideo(target,url) { $("#"+target).oembed(url); return false; } Here is an example of ...

Discovering the correct method to access a slug from an API endpoint in NextJS v14's "App Router"

In my Next.js 14 application, I am utilizing the folder structure src/app/api/. Within this structure, there is a route.ts file located at src/app/api/v1/confirmation-codes/[confirmationCode]/route.ts. After extensive searching through the documentation, ...

js.executeScript produces a Unexpected identifier error

Visit this link for proofs Running a script in the browser console on the specified page: let img = document.querySelector('.subscribe'), style = img.currentStyle || window.getComputedStyle(img, false), bi = style.backgroundImage.slice(4, -1).re ...

Is it possible to perform bulk deletes using Sequelize?

Why isn't my code working when trying to delete multiple ids by entering them as an array? name: 'Test 2: hard delete test', condition: { id:[5,6,7]} }, ]; const hardDeleteTestResults = []; for (const test of hardD ...

Tips for accessing information from different sources within Vue 3

In my Vue 3 setup() method, I have an array [] stored as a constant. This array consists of X objects and represents the responses of a form. My goal is to showcase each object on a single dynamic page within our internal dashboard by using v-for in the t ...