Unveiling the secret to eliminating repetitive items from a JSON array

In my JSON array, I have entries like this:

daysdif = [{
  "EmployeeID": "213654654",
  "DaysDiff": "NaN"
}, {
  "EmployeeID": "String",
  "DaysDiff": "NaN"
}, {
  "EmployeeID": "6021240",
  "DaysDiff": "-63.30"
}, {
  "EmployeeID": "6011327",
  "DaysDiff": "-35.67"
}, {
  "EmployeeID": "883",
  "DaysDiff": "-63.40"
}, {
  "EmployeeID": "1183",
  "DaysDiff": "-70.13"
}, {
  "EmployeeID": "1240",
  "DaysDiff": "-70.97"
}, {
  "EmployeeID": "2293",
  "DaysDiff": "-63.30"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-8.47"
}, {
  "EmployeeID": "3395",
  "DaysDiff": "-68.00"
}, {
  "EmployeeID": "2473",
  "DaysDiff": "-66.20"
}, {
  "EmployeeID": "1075",
  "DaysDiff": "-70.17"
}, {
  "EmployeeID": "2947",
  "DaysDiff": "-69.10"
}, {
  "EmployeeID": "5002196",
  "DaysDiff": "-4.97"
}, {
  "EmployeeID": "1688",
  "DaysDiff": "-67.40"
}, {
  "EmployeeID": "2031",
  "DaysDiff": "-54.07"
}, {
  "EmployeeID": "1484",
  "DaysDiff": "-69.17"
}, {
  "EmployeeID": "1022",
  "DaysDiff": "-69.40"
}]

Among the entries, there are duplicates with the same 'EmployeeID' but different 'DaysDiff' values. For example:

[{
"EmployeeID": "5001839",
  "DaysDiff": "-8.47"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-22.20"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-23.77"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-41.67"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-63.97"
}]

I am looking to keep only the entry with the highest 'DaysDiff' value for each duplicate 'EmployeeID'. In this case, it would be '-8.47' and remove the other duplicate entries.

Answer №1

Here is my approach using underscore.js:

json_data = [
  {
    "EmployeeID": "213654654",
    "DaysDiff": "NaN"
  },
  {
    "EmployeeID": "String",
    "DaysDiff": "NaN"
  },
  ...
  {
    "EmployeeID": "1022",
    "DaysDiff": "-69.40"
  }
]

grp_json = _.groupBy(json_data, "EmployeeID")

new_list = []

_.each(grp_json, function(i) { 
  get_max = _.max(i, "DaysDiff")
  if( get_max == -Infinity) { 
    new_list.push(i[0])    
  }
  else {
    new_list.push(get_max)
  }
})

console.log('new_list', new_list)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Answer №2

Give this a shot...

let employeesList=[];
for(let employee in daysDifference){
    if(employeesList.indexOf(daysDifference[employee]['employeeID'])!=-1){
        daysDifference.splice(employee,1);
    }else{
        employeesList.push(daysDifference[employee]['employeeID']);
    }
}
console.log(daysDifference);

Answer №3

Please attempt this out:

var dataValues = [{
  "EmployeeID": "213654654",
  "DaysDiff": "NaN"
}, {
  "EmployeeID": "String",
  "DaysDiff": "NaN"
}, {
  "EmployeeID": "6021240",
  "DaysDiff": "-63.30"
}, {
  "EmployeeID": "6011327",
  "DaysDiff": "-35.67"
}, {
  "EmployeeID": "883",
  "DaysDiff": "-63.40"
}, {
  "EmployeeID": "1183",
  "DaysDiff": "-70.13"
}, {
  "EmployeeID": "1240",
  "DaysDiff": "-70.97"
}, {
  "EmployeeID": "2293",
  "DaysDiff": "-63.30"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-8.47"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-22.20"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-23.77"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-41.67"
}, {
  "EmployeeID": "5001839",
  "DaysDiff": "-63.97"
}, {
  "EmployeeID": "3395",
  "DaysDiff": "-68.00"
}, {
  "EmployeeID": "2473",
  "DaysDiff": "-66.20"
}, {
  "EmployeeID": "1075",
  "DaysDiff": "-70.17"
}, {
  "EmployeeID": "2947",
  "DaysDiff": "-69.10"
}, {
  "EmployeeID": "5002196",
  "DaysDiff": "-4.97"
}, {
  "EmployeeID": "5002196",
  "DaysDiff": "-39.23"
}, {
  "EmployeeID": "5002196",
  "DaysDiff": "-58.73"
}, {
  "EmployeeID": "1688",
  "DaysDiff": "-67.40"
}, {
  "EmployeeID": "2031",
  "DaysDiff": "-54.07"
}, {
  "EmployeeID": "1484",
  "DaysDiff": "-69.17"
}, {
  "EmployeeID": "1022",
  "DaysDiff": "-69.40"
}];

var updatedData = [];
var isPresent = true;;

dataValues.forEach(function(item){
  isPresent = true;
  if(item["DaysDiff"] !== "NaN"){
    updatedData.forEach(function(obj){
        if(obj["EmployeeID"] == item["EmployeeID"]){
            updatedData["DaysDiff"] = Math.max(parseFloat(item["DaysDiff"]), parseFloat(updatedData["DaysDiff"])).toString();
          isPresent = false;
        }
    });
        if(isPresent){
            updatedData.push(item);
        }
    }
});
console.log(updatedData);

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

Once the timer has finished, I would like for a specific component to be displayed

I am trying to make my component CountDownSquare disappear once the timer has fully counted down. In my homePageData, I have the main text stored in a h3 element that should only appear once the countdown is complete. I attempted to use a ternary stateme ...

Controlling the Flow of Events in JavaScript Documents

Explore the integration of two interconnected Javascript files and delve into managing event propagation between them effectively. 1st js file var red = [0, 100, 63]; var orange = [40, 100, 60]; var green = [75, 100, 40]; var blue = [196, 77, 55]; var ...

What steps can I take to prevent my menu items from overlapping in the mobile navigation menu?

I am currently working on creating a mobile menu, but I'm facing an issue where the menu items overlap when hovered over. Instead, I want the menu items to move downwards when hovered upon to prevent the text from overlapping. Below is the HTML code ...

Discover the best method for summing all values within a JSON object that contains multiple unique keys

What is the best way to sum up all values in a JSON object? The object provided below contains values that are in string format and it has different keys. var numbers = { x: "4", y: "6", z: "2" }; The result should be: total ...

Unable to load JSON model texture

I successfully transformed an obj file into a json model using a Python tool, and now I am attempting to load it into my project. Below is the code snippet: var camera, scene, renderer; var mesh, aircraft; function addModelToScene( geometry, materials ) ...

Attempting to send a String in a particular structure

I'm facing an issue with the format I'm trying to pass. The expected format should be like this: [{"blah.png"},{"blah2.png"}] However, instead of getting the desired format, I am receiving this: ["blah.png","blah2.png"] Below is the code snip ...

What are the solutions to repair a triple drop-down menu?

I am struggling with the code below which contains numbers inside the values: What I need is to modify all instances of the following codes: <option value="1" class="sub_1"> To look like this: <option value="" id="1" class="sub_1"> Basical ...

"Utilize URL parameters to specify a date range when working with Django Rest

In my JSON structure, I have data entries with timestamps and names: [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-20 03:26:53", "name": "ab" }, { "date": "2017-12- ...

Encountering invalid parameters while attempting to utilize the track.scrobble service from the Last.Fm API in a Node.js application

After successfully completing the Last.Fm authentication process following the instructions provided here, I received the session key without any issues. However, my attempts to make an authenticated POST request to the track.scrobble method of the Last.Fm ...

Display the count of ng-repeat items beyond its scope

Currently, I am looping through a list of nested JSON objects in this manner: <div ng-repeat='item in items'> <ul> <li ng-repeat='specific in item'>{{specific}}</li> </ul> </div> I want to ...

What is the procedure for opening a page within a dialog box with jQuery?

When the user clicks on the 'login' link, I want to display the login.aspx page in a dialog box. I've explored jQuery UI Dialog, but it seems incapable of opening entire pages from a specified URL. Are there any suggestions or alternatives ...

Using a structural directive in Angular 2 that accepts a String as an input

I am attempting to develop a custom structural directive using the example provided here When trying to pass a string as an input with a slight modification, I encountered an issue where the input value was returning 'undefined' when calling th ...

Node.js and Angular.js communication: from requests to responses

Efforts are being made to solicit data from a node.js server through angular.js. However, an unexpected challenge persists: post-data response, a stark white browser screen shows up with the JSON object in plain sight. The goal is for angular.js to acknowl ...

Retrieve specific JSON objects based on unique attribute identifiers

My current project involves utilizing a .json file to generate a series of objects that will be utilized on various pages throughout our website. I am implementing the getJSON function in Jquery to pull these objects into different sections of the site whe ...

Doubt surrounding the behavior of Node.js when a file is required that does not export anything from a module

My understanding of Node.js' require() function and module.exports is high-level, but I still find some behaviors confusing. Imagine I have two simple one-line files named a.js and b.js. In a.js: require('./b.js'); and in b.js: console. ...

PHP Notification: Attempting to access a property of an invalid type object

I am currently utilizing the Factory in AngularJS and here is the script I am using: app.factory('GetCountryService', function ($http, $q) { return { getCountry: function(str) { // The $http API is based on th ...

Establish the state as the result of a function

I need to update the state of timeToCountdown with the value stored in allTimeInSeconds. Next, I intend to pass this data as a prop to a component. class Timer extends Component { constructor(props){ super(props); this.state = { ...

Tips for effectively showcasing JSON in an Angular directive

I am facing an issue with my Angular app that utilizes ui-router. I have set up a service and directive, but I am unable to display JSON data. Surprisingly, it works perfectly fine without the directive when I directly display it in the main template (home ...

What is the best way to divide my Vue.js project into separate sections for development and testing purposes?

I am looking to split my vuejs frontend project into two sections: development and testing. For the development section, I want to work locally and make requests to the example:8010 url, while for the testing section, I need to send requests to the example ...

JavaScript: What is the best way to loop through specific properties of a JavaScript object?

I have a JavaScript object structured as follows: const columns = { firstLabel: 'Hello', secondLabel: 'world', thirdLabel: 'I', fourthLabel: 'Am', fifthLabel: 'Paul', }; My goal is to e ...