Javascript tip: Eliminating duplicate values with identical keys in an object

Having an array of objects where one key:value pair has duplicate values, I'm looking to eliminate the replicated values within each object.

For instance, I need to trim the duplicate values from mapDataWithDuplicate, as shown below:

mapDataWithDuplicate=[
    {
      lat: "39.562686920166", 
      lng: "-105.106826782227",  
      storeId: "0839", 
      stopId: "12,1,12,23,23"
    },
    {
      lat: "39.6455154418945", 
      lng: "-105.339477539063", 
      storeId: "0010", 
      stopId: "24,2,13,24,13,2,13,24,24"
    }
]

The goal is to remove duplicate values from stopId and arrange it in ascending order. Any assistance would be greatly appreciated.

The expected output should resemble this:

mapDataWithDuplicate=[
        {
          lat: "39.562686920166", 
          lng: "-105.106826782227",  
          storeId: "0839", 
          stopId: "1,12,23"
        },
        {
          lat: "39.6455154418945", 
          lng: "-105.339477539063", 
          storeId: "0010", 
          stopId: "2,13,24"
        }
    ]

Answer №1

Utilize the Array.map method to loop through each item and transform the stopId into a Set, eliminating duplicate values and delivering the final outcome.

const mapDataWithDuplicate = [
  {
    lat: "39.562686920166",
    lng: "-105.106826782227",
    storeId: "0839",
    stopId: "12,1,12,23,23"
  },
  {
    lat: "39.6455154418945",
    lng: "-105.339477539063",
    storeId: "0010",
    stopId: "24,2,13,24,13,2,13,24,24"
  }
]

const processData = (list) => {
  return list.map(data => {
    const set = new Set(data.stopId.split(","));
    const ids = [...set].sort((num1, num2) => num1 - num2);
    const stopId = ids.join(",");
    return { ...data, stopId };
  });
}

console.log(processData(mapDataWithDuplicate));

Answer №2

If you're open to leveraging a library, this method stands out as the most efficient way to achieve both tasks

var _ = require('lodash');

mapDataWithDuplicate.forEach(e => {
  const convertToArray = _.map(_.words(e.stopId), _.parseInt)
  console.log(_.uniq(_.sortBy(convertToArray)));
})

Initially converting the string into an array is necessary before proceeding with execution. Ideally, having your data in integer format from the start would eliminate this extra step.

Although there's a function that combines both actions, I encountered some issues using it. Perhaps you could give it a try and see if it works for you. Here's the relevant documentation: https://lodash.com/docs/4.17.15#sortedUniq

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

How to transfer data using props through the ":to" attribute of a router link in Vue.js

I am facing an issue with creating a router-link in Vue and passing a route name as a prop. What I am trying to achieve is the following: <template> <div> <router-link :to="myProps">Login</router-link> </div> </tem ...

Discovering the FindOne() model in Nodejs Sequelize comes with values that are either rounded or truncated

Running the code below, I am attempting to retrieve data from an sqlite database connected to locally. The current snippet is a test to fetch data: console.log('debug after here.'); const tag = await Tags.findOne({ where: { guild: message.guild ...

Utilizing data from a JavaScript array and merging it with basic HTML structure

Every day, a js array source on a remote server gets updated: var io = new Array(); nsi[0] = new Array('','Frank','','Factory worker','Mercedes',374.0,26.2,76,181,'',75,'Audi',1456.5,27 ...

The Angular route functions flawlessly in the development environment, but encounters issues when deployed to

I have a project built with Angular 2, During development on localhost, everything runs smoothly. However, once I build a production version using (npm run build: prod) and navigate to the route on the server, I encounter a 404 error indicating that the r ...

sending byte array from php: a step-by-step guide

I'm currently facing an issue with sending a byte array of an image to my webservice within a JSON object. Strangely, when the request is made with just an empty array, it successfully hits the server and returns the JSON response. Below is the code s ...

Can you clarify the concept of closures and how they bind the loop counter to the function scope?

I have observed programmers setting up event listeners inside loops, utilizing the counter. The syntax that I have come across is as follows: for(var i=0; i < someArray.length; i++){ someArray[i].onclick = (function(i){/* Some code using i */})(i); ...

Maintaining the current image while awaiting the completion of the new image update

I have successfully implemented a script using setInterval along with the jQuery load function to periodically update an image tag. var refresh_days = setInterval(function() { $('#box_name').load("dynamic.php");}, 1000 ); While this setup wo ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

How to make Angular 5 wait for promises to finish executing in a for loop

My task involves working with an array like this: arr = ['res1', 'res2', 'res3']; For each value in the arr, I need to make an API call that returns a promise. arr.forEach(val => this.getPromise(val)); The getPromise me ...

utilizing angular directives on a group of elements

Is there a more efficient way to disable all form elements in a large form with multiple tabs when a specific condition is met? I could go with <input ng-disabled="myCondition()">, but it would require adding this code in many places, leading to pote ...

Arranging Material UI tabs on both sides

I'm currently working with Material UI tabs and I'm trying to achieve a layout where some tabs are positioned to the left and others to the right. For instance, if I have 5 tabs, I want 3 on the left and 2 on the right. I've tried placing th ...

I am experiencing an issue with the Search Filter where it is not successfully removing

My goal is to filter colors when a user searches for a color code. Currently, the search function displays the correct number of filtered items, but the color bubbles are not being removed as intended. I am working on removing the bubbles when a search is ...

Arrange the keys of a map in ascending order, prioritizing special characters and their precedence

JavaScript ES6 Map Example: const map = new Map(); map.set('first', ['1', '2']); map.set('second', ['abc', 'def']); map.set('_third', []); map.set(')(*', []); map.set('he ...

Creating mutual reactivity between two inputs in Vue.js

I am in the process of creating a tool that calculates the cost of purchasing specific materials. One challenge I'm facing is that users sometimes buy by mass and other times by volume. My goal is to have two active input fields (one for mass and one ...

Adjusting the size of text in KineticJS to ensure it fits comfortably within a rectangle while

Check out this link: http://jsfiddle.net/6VRxE/11/ Looking for a way to dynamically adjust text, text size, and padding to fit inside a rectangle and be vertically aligned? Here's the code snippet: var messageText = new Kinetic.Text({ x: .25* ...

Issues encountered when attempting to incorporate additional sliders using JavaScript within a single webpage

I've been working on integrating a new slider into my website (it would be the 3rd one as I already have 2), but I'm facing some difficulty. I am using JavaScript, but struggling with how to assign and manage the slide numbers like (1,0) or (1,1) ...

Run XQuery dynamically in JavaScript and store the outcome in a JavaScript variable

Looking to achieve the following: Running a dynamic XQUERY stored in a JavaScript variable example var myxquery = For Channels.Channel where Channel/availability = yes And Channels.Channel/Label = 'CNN' Return EXIST(Channels.Channel/Id)&apo ...

Accessing an item within a JSON object using jQuery

Trying to access an element within a JSON object, part of the code is shown below: { " academy": { "business": { "E-commerce": [ I have successfully accessed the academy as the first element using the following code: $.getJSON("p ...

Updating the time and date format within an AngularJS application

I am receiving date and time data from the API and would like to adjust the format. The current format is "2016-05-12", "07:17:35". Desired format: 12-May-2016 7:30 PM: <table class="table"> <thead> <tr> <th& ...

Updating an array element in Mongoose, the MongoDB ORM

I am currently in the process of making changes to a MongoDb collection that contains an array of documents called items. To achieve this, I am utilizing the express and mongoose frameworks. This is how my schema is structured: const mongoose = require(" ...