Find similarities between two arrays and eliminate any duplicates from one of them

const names = ["Daniel", "Lucas", "Gwen", "Henry", "Jasper"];
const random = ["hi", "Lucas", "apple", "banana", "Jasper", "hello", "meow"];

I am looking to compare the arrays names and random. If there are any duplicates in the random array, I want to remove them and achieve an outcome like this:

const newArr = ["hi", "apple", "banana", "hello", "meow"]

Can you guide me on how to accomplish this?

Answer №1

const names = ["Emma", "Ethan", "Ava", "Mia", "Oliver"];
const random = ["hello", "Ethan", "kiwi", "pear", "Oliver", "hey", "woof"];
const result = random.filter(name => !names.includes(name))
console.log(result)

Answer №2

This is just a basic filter function

const filteredArray = random.filter(item => !names.includes(item))

Answer №3

If you're looking to eliminate duplicates from a list, one way to do it is by using the filter method like so:

const newArr = random.filter(name => ! names.includes(name));

This approach works well for a small number of values, but may not be efficient for larger datasets.

The time complexity of this method is O(n^2), where n represents the size of both lists. Each element in random is compared against all elements in names.

For handling a large amount of data, consider implementing a Map structure instead.

const names = ["Daniel", "Lucas", "Gwen", "Henry", "Jasper"];
const random = ["hi", "Lucas", "apple", "banana", "Jasper", "hello", "meow"];

const namesMap = new Map();
for (const name of names) namesMap.set(name, true);

const newArr = [];
for (const rand of random) {
  if (namesMap.has(rand)) continue;
  newArr.push(rand);
}

Despite the additional loop, the overall time complexity remains O(n) due to the iteration through both lists, which simplifies to O(2n) or just O(n).

Keep in mind that while this method is more efficient for larger datasets, it might sacrifice some readability.

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

The function has not been defined in HOC

Trying to incorporate a simple HOC in REACT, but I keep encountering this persistent error. (0, _hocFunctionName.hocFunctionName) is not a function If you want to take a look at the sandbox, you can find it HERE I've been troubleshooting and resea ...

How to troubleshoot Props not functioning in nextjs-typescript?

I'm having trouble with props in my project and I can't seem to figure it out! Here are the three files. I'm still learning typescript but everything seems fine in the code, yet it's not working! Here is index.tsx file: const Home: ...

I'm looking for a solution to resolve the error occurring in my Angular component

[{ "resource": "/c:/Users/User/Desktop/ang/firstapp/src/app/app.component.ts", "owner": "typescript", "code": "7016", "severity": 8, "message": "Error encountered: 't ...

Detecting readiness of video playback on mobile devices using Three.js

When using a video on a sphere texture, I am facing an issue where the sphere only appears once the video has loaded. However, on mobile devices, there is a black sphere shown initially when the video has loaded, and then after a few seconds, the video sta ...

Sending a JSON object with scheduled task cron job

I have a PHP cron job that is quite complex. It retrieves data from an external webpage and consolidates all the information into one variable, encoding it in JSON. Unfortunately, this entire process is slow and consumes a significant amount of time. My d ...

Using an npm package in client-side JavaScript

I've been exploring client-side GitHub packages recently and came across developers mentioning that the packages can be downloaded using npm. This confuses me as I thought these were client-side JavaScript packages. They also mentioned something about ...

Issue with configuring ExtJS combo box

While using combos in an input form, I encountered an intriguing issue. The form has combos that retrieve data from JSON stores. Everything works smoothly when adding a new record, but when editing an existing one, the ID sometimes appears selected instead ...

Sending numerous arrays to MongoDB through a Post route in NodeJS

Currently, I am in the process of developing a basic tool for inserting recipes using NodeJS and MongoDB as part of my learning journey with the MEAN stack. Each recipe consists of a title, description, and multiple ingredient arrays which contain the name ...

The picture is undergoing compression during the upload process to Cloudinary

I've been working on a code snippet to upload images to cloudinary. let imageArr = []; if (media) { media && imageArr.push(media.thumbUrl); } let resultPromise = imageArr.map(async (img) => { await cloudinary.upload ...

Encountering the issue of receiving an undefined class when using the img tag in a

In my React.js project, I encountered an issue where the class for the img tag is appearing as undefined. The problem lies within the Header.jsx component. In this file, I am using the <img> tag but the CSS properties are not being applied to the ima ...

"Failure to update the $scope object within an AngularJS service results in no changes being reflected in

I am currently working on integrating Google maps into an Angular / IonicFramework project. The implementation involves a directive, a service, and a controller. Within the scope ($scope), I have objects for the map, marker, and geolocation. While the map ...

What is the best way to identify the position of an element in an array given my specific circumstances

I am trying to utilize the ng-repeat directive in order to display an array. Here is what I have: <div ng-repeat="stu in school"> <div>{{stu.name}}</div> <div>{{stu.grade}}</div> </div> JavaScript $scope.scho ...

Switch navigation - always display the menu on the existing page

I have a toggle menu implemented. Please check out the code and functionality on JsFiddle When clicking on a h3 tag like Category 1 (which is an a tag), the menu opens and remains open on the current page. However, if you click on the h3 tag (Category1) ...

Changing objects that have been assigned the same value

Currently, I am assigning one array to another array. For example, let's assign array X to array Y. If I perform any operations or change the values of array X, will array Y also be affected? Initially, I would think the answer is no, but I am expe ...

Looping through an array of items and computing the mean value

Given the current data structure, my goal is to calculate the average value for each column across all items in the contenders object. The next step is to convert this information into an array of arrays. Each subarray should consist of two values: the rou ...

Attempting to rearrange the table data by selecting the column header

In an attempt to create a table that can be sorted by clicking on the column headers, I have written code using Javascript, HTML, and PHP. Below is the code snippet: <?php $rows=array(); $query = "SELECT CONCAT(usrFirstname,'',usrSurname) As ...

Cracked Code at Position 880 (LeetCode)

Given an encoded string S, the decoded string is determined by reading each character and following the steps below: If the character is a letter, it is written directly onto the tape. If the character is a digit (denoted as d), the current tape i ...

Ways to generate an element with a specific identifier using a single line of code

When creating an element, I often use the following syntax: var foo = document.createElement('div'); To set the ID of the div, I would typically do this: foo.setAttribute('id', 'divName'); After some searching online, I ca ...

Detecting Selected Radio Button Value Using Javascript

I am currently working on a project titled: Tennis Club Management utilizing javascript, HTML, CSS, and Bootstrap. In the project, one of the pages is managePlayers.html, which features two buttons - Add Players & Show Players. Clicking on the Add Play ...

Issues with React Native: Struggling to iterate through an array and show it with an image URL stored

Just diving into React and I'm facing a challenge with my code. I have an array stored in my .state that I want to loop through and display the images. (I'm using 'Image' and a Card object from https://github.com/lhandel/react-native-ca ...