Utilize lodash to filter an array into unique and duplicate elements exclusively

My goal is to achieve the following using lodash:

starting from

["place of interest", "sightseeing", "monument", "museum", "sightseeing", "museum", "citylife", "monument", "monument"]

I am looking for an array with unique elements only

["place of interest", "sightseeing", "citylife"]

and a separate array containing duplicates, but eliminating any duplicate duplicates! :)

["museum", "monument"]

Answer №1

To achieve this task, you can utilize the _.countBy() and _.transform() functions in order to generate the arrays (check out the example):

var arr = ["place of interest", "sightseeing", "monument", "museum", "sightseeing", "museum", "citylife", "monument", "monument"];

_(arr).countBy(function (item) {
    return item;
}).transform(function (result, n, key) {
    result[n === 1 ? 'unique' : 'duplicates'].push(key);
}, { unique : [], duplicates : [] }).value();

Additionally, here is an alternative solution using only JavaScript (view on JSFiddle):

var arr = ["place of interest", "sightseeing", "monument", "museum", "sightseeing", "museum", "citylife", "monument", "monument'];

var counts = arr.reduce(function (items, item) {
    items[item] = (items[item] || 0) + 1;
    return items;
}, {});

var results = Object.keys(counts).reduce(function (result, key) {
    result[counts[key] === 1 ? 'unique' : 'duplicates'].push(key);
    return result;
}, {
    unique: [],
    duplicates: []
});

console.log(results);

document.getElementById('output').innerText = JSON.stringify(results);

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

What is preventing me from being able to use object spread results in TypeScript casting?

Uniqueness in Question My inquiry was not aimed at identifying the type or class name of an object. Rather, it delved into the concept of "casting" an object to a specific type, which arose from a misconception about TypeScript and its functionality. This ...

Automate page refresh using Selenium in Java until target element becomes visible

Is there a way to have selenium wait for 3 minutes before refreshing the page until a specific element (in this case, the Download button) is found? I've attempted the code below, but it doesn't seem to be effective. Note: I am trying to upload ...

Update the displayed image on the webpage based on information retrieved from the database

Can someone help me figure out how to change the clickable icon on getseats.php from available to unavailable when a seat's status is 0? I'm struggling with this and any advice would be appreciated. Here's the code I have: <?php $noerro ...

JavaScript Email Verification

I am designing my website and encountering an issue with the email checker. I can't figure out why it's not working, especially since I have never used JavaScript before. This is what I tried: var flag=true; var st = Form1["email"].value.ind ...

What is the process for retrieving the information sent from the client application to the jsreport server?

I want to create a downloadable pdf report through my angular application using jsreport. The client app makes a POST request passing sample data to the report server in this manner. $http.post('http://localhost:5488/api/report', { ' ...

Learn how to pass an id from the query parameters to the getInitialProps function in Next.js

Looking to create a basic website that displays content from a database? Utilizing the getInitialProps function from Next.js documentation can help with server-side rendering: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialpr ...

In Nodejs, the function 'require' fails to load a module when using specific filenames

Hello everyone, I am a long-time user but this is my first time asking a question. So, I have a file named file.js where I am trying to require another file called user.service.js at the beginning of the file: var userService = require('./user.servi ...

"Presenting Invoice Information on an Invoice Template: A Step-by-Step Guide

Currently, I am working with Laravel 5.7 and VueJs 2.5.*, where I have a table of invoices. My goal is to create a new component that will display a specific invoice based on user selection, allowing them to view or print the chosen invoice. I am still ex ...

What is the procedure for transforming XML data elements into a unified associative array within PHP programming?

I'm dealing with a PHP code snippet that generates an object variable containing XML data structured like this: <food1> <name1>Belgian Waffles</name1> <prices1> <price1>$5.95</price1> <pr ...

Guide on converting a material datepicker date value into the format "MM-DD-YYYY" in Angular 6

I need help formatting the date below to MM-DD-YYYY format in my Angular 6 project. I've checked out various solutions on SO and other websites, but so far, none have worked for me. Currently, I am using Material's Angular DatePicker component. ...

The start screen fails to display when clicking the restart button

I am struggling to get the restart button to display the start screen again. Even though I have called the restart function within the clearColors function, which should show the start screen, it hasn't been effective so far. Initially, in the fadeOut ...

Guide to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...

Building a Julia array element by element in a streamlined mannerORCreating a Julia array

Looking for the most efficient method to construct a Julia array element by element when unsure of the final array size? Building the array within a single for loop is the challenge at hand. Exploring two options thus far: pushing values into the array or ...

As you scroll, the header gradually reduces in size, but at the point where the reduction occurs, a slight flick

As I develop a website, I have implemented a sticky header that shrinks after scrolling past the window height. I experimented with two versions - one using Vanilla-JS and another with jQuery. Both versions work fine, but the issue arises when the header s ...

Chrome console displaying error: "API request open method is not a function."

Check out my weather app on Code Pen Here's the code for my weather app (apologies if it's overwhelming): var button=document.getElementById('submit'); var zipcode; var lat; var lng; var weather; var iconId; var temp; // Function t ...

Alert and console.log continue to show the error message: 'Uncaught TypeError: Cannot read property ' ' of undefined

Encountering a Uncaught TypeError: Cannot read property 'valeurs' of undefined, however the alert() and console.log() functions are successfully displaying the data. Below is the code snippet: var item = document.getElementById('inputData&a ...

AJAX Form Submission for CommentingAJAX allows for seamless form submission

Currently facing an issue with a form submission that is not displaying comments without refreshing the page. When the submit button is clicked, it redirects to the top of the page without executing any actions - no insertion into the database and subseque ...

Develop a list of findings from the search

Is there a way to extract the name from the image shown below? return testData.then((data) => { console.log(data) var results = []; var toSearch = params.suggestTerm; data = data["data"]["0"]; console.log(" ...

Error Checking in AngularJS Form Submission

According to my form.json file, I have a form that needs validation and a simulated submission. Firstly, I need to address this issue: fnPtr is not a function Next, I want to submit the form to a mocked API endpoint that will return true or false. Can I ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...