Utilizing Lodash's uniqWith function, it allows us to specify how we want to

Currently, I am utilizing the lodash uniqWith method to eliminate duplicate items with the same id from my array.

However, the lodash method retains the first duplicated item, whereas I actually want to keep the last duplicated item.

Is there a way to achieve this?

var result = _.uniqWith(editedData, function(arrVal, othVal) {
      return arrVal.id === othVal.id;
    });
    console.log(result)

Answer №1

To implement a uniqueByLast function utilizing the _.flow() method, you can employ _.keyBy() to create an object based on 'id', and then use _.values() to convert it into an array:

const { flow, partialRight: pr, keyBy, values } = _

const lastUniqBy = iteratee => flow(
  pr(keyBy, iteratee),
  values
)

const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]

const result = lastUniqBy('id')(arr)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Similarly, you can achieve the same functionality using lodash/fp:

const { flow, keyBy, values } = _

const lastUniqBy = iteratee => flow(
  keyBy(iteratee),
  values
)

const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]

const result = lastUniqBy('id')(arr)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

Answer №2

The simplest method? Start by reversing the array (make sure to clone it first to prevent any changes).

var output = _.uniqWith(_.reverse(_.clone(editedData)), function(arrayValue, otherValue) {...});

You could also streamline your code like this:

var output = _.uniqWith(_.reverse(_.clone(editedData)), ({ id: x }, { id: y }) => x === y);

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

Creating a script within a newly generated division element

function addNewChild() { if (childCount <= 2) { childCount++; var newDiv = document.createElement('div'); newDiv.innerHTML = '<br> Prescription '+childCount+':<br><input id="uploadFile" class="disabl ...

What is the process for pulling out a specific JSON element based on a condition?

I am working with a JSON object that looks like this: "links" : [ { "rel" : "first", "href" : "http://localhost:8080/first" }, { "rel" : "self", "href" : "http://localhost:8080/self" }, { "rel" : "next", "href" : "http://loca ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

Is there a way to pass a variable to the callback function in a request?

My current approach involves using express and request to convert a website's HTML into JSON, and then sending it back as a response. Here is an example: app.get('/live', function(req, _res){ res = _res; options.url = 'http://targe ...

What are the comparable Java and JavaScript methods for commands used in Selenium?

Today marks my second day delving into the world of selenium. I can't help but wonder if there's a resource out there that lists selenium commands along with their corresponding javascript or java methods. I'm currently working on creating ...

assign the values of variables from one array to variables in a different array

Hey everyone, I'm dealing with a set of SAS dates (18141 to 18414) and a range of ID numbers (m101-m254). What I need is for every date within the range to appear once for each ID value in the specified range like so: date id 18141 m101 18142 m101 1 ...

I possess a certain input and am seeking a new and distinct output

I am looking to insert a word into an <input> and see an altered output. For example, Input = Michael Output = From Michael Jordan function modifyOutput() { var inputWord = document.getElementById("inputField").value; var outputText = "print ...

Sorting a List with jQuery Using Anchor Tags and 2 Criteria

I am currently developing a jQuery filter that allows users to filter a list based on two criteria sets - fruit type and color. For instance, if the user selects "Berry" as the fruit type, only berries will be displayed. Subsequently, if they choose "Red" ...

Extraction of nested JSON data and loading it into a PostgreSQL table

After using the query below to parse and store JSON elements into the 'pl' table, I encountered an issue where I was unable insert it into another table using json_populate_recordset: select each_attribute ->> 'id' ...

Retrieving JSON Arrays in PHP through an AJAX Request

Having trouble extracting data from multiple arrays in an AJAX request. Can anyone help? Here's what I'm trying to send: https://i.stack.imgur.com/4MEL4.png Executing a jQuery AJAX POST to a PHP file, but uncertain how to retrieve the data. An ...

What is the best way to combine a 2D matrix with a 3D matrix in Python?

Looking at my 3D matrix represented by the variable a, it appears as follows: a=np.array([[[1,2],[2,3]],[[3,4],[4,5]]]) [ [[1 2],[2 3]] [[3 4],[4 5]] ] a.shape (2, 2, 2) My goal now is to append another element, such as [[5,6],[6,7]], to this array. Th ...

The message "Error: Cannot set headers after they have been sent" may occur when using Express Static and setHeaders together

Encountering the Error: Can't set headers after they are sent. message when running the following code. app.use('/assets/u', express.static('./public/img/u', { setHeaders: (res, path, stat) => { redis.get(`image-mime:1`, ...

Capturing dynamic text from a URL using Protractor and Node.js

How can I extract the 'PR001-CC001234' segment from a URL using Protractor in Node.js? While I am able to retrieve the current URL and save it as a variable, I am seeking assistance in extracting the dynamic text at the end of the URL. http://exa ...

Modify the string by replacing the second comma with a line break

Looking for a solution to insert a line break after the second comma in a string. The code I'm currently using works, but I'm wondering if using a regex would be a more efficient approach. var data = $('#test1').html(); var position ...

Encountering a 'next' error with Facebook Connect

I'm currently in the process of testing out the new Facebook authentication system, but I'm facing some issues with getting the login to function properly. Here's the error message I'm encountering: API Error Code: 100 API Error Desc ...

Getting parameters from a URL with a React frontend and Express backend: A step-by-step guide

I am currently developing a react application with an express backend. I am in the process of integrating socket io chat functionality into the frontend. Everything is functioning properly, but I am now looking to extract parameters from the URL in order t ...

Arranging words in alphabetical order C

My current exercise involves sorting words in a 1D char array. The code I've written is almost functional, but it consistently overlooks the last character of the final word. Below is the code snippet with some comments to improve readability. I ackno ...

What could be causing the sluggishness in my jQuery script that checks for required input fields?

My goal is to utilize jQuery to check for required input fields in browsers that do not recognize the required HTML tag. Below is the jQuery script I am using. $('div').on('submit', '#myform', function(e){ e.stopProp ...

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

Update the property prior to calling window.confirm()

Take a look at my code snippet: <a @click="destroy" :class="['button', { 'is-loading': deleting }]" > Delete </a> data: () => ({ deleting: false }), destroy () { this.deleting = true if (!confirm('Are ...