Removing duplicates from a multidimensional array by comparing the first element in each subarray using Javascript

I need to obtain unique values from a multidimensional array.

The uniqueness should be based on the first element of each item.

let arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4'], ['item 6', 'item 5']]

For example, if item 1 is repeated, it should result in

let arr = [['item 1', 'item 2'],['item 3', 'item 4'], ['item 6', 'item 5']]

I attempted this solution but it currently checks every single element for uniqueness

 var uniques = [];
  var itemsFound = {};
  for (var i = 0, l = arr.length; i < l; i++) {
    var stringified = JSON.stringify(arr[i]);
    if (itemsFound[stringified]) {
      continue;
    }
    uniques.push(arr[i]);
    itemsFound[stringified] = true;
  }
  return uniques;

Answer №1

The code provided will generate the same output as shown, but it is tailored for two-dimensional arrays like the one in your example:

const arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4'], ['item 6', 'item 5']];
const arr2 = Array
    .from(
        new Map(
            arr.reverse()
        )
    )
    .reverse()
;
console.log(JSON.stringify(arr2));
// -> [["item 1","item 2"],["item 3","item 4"],["item 6","item 5"]]

If Object.fromEntries is available, an alternative implementation could be:

const arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4'], ['item 6', 'item 5']];
const arr2 = Object
    .entries(
        Object.fromEntries(
            arr.reverse()
        )
    )
    .reverse()
;
console.log(JSON.stringify(arr2));
// -> [["item 1","item 2"],["item 3","item 4"],["item 6","item 5"]]

However, this might be less performant compared to the previous method.

If you want to skip repeated values at any position within the inner array, additional steps are needed:

In the input example, 'item 5' is repeated but is ignored because its first occurrence is with 'item 1'.

Adding a new element like ['item 7', 'item 6'] would pass in the previous example:

// ...
// -> [["item 1","item 2"],["item 3","item 4"],["item 6","item 5"],["item 7","item 6"]]

To account for all elements and scan all sub-elements, you can use the following approach:

const arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4'], ['item 6', 'item 5'], ['item 7','item 6']];
const seen = new Set();
const arr2 = arr
    .filter(function hasRepetition(items) {
        if ( // Repetition found
            1 + items.findIndex(itm=>seen.has(itm))
        ) return false;
        items.map(seen.add, seen);
        return true;
    })
;
console.log(JSON.stringify(arr2));
// -> [["item 1","item 2"],["item 3","item 4"],["item 6","item 5"]]

This solution also works for arrays of any dimensions.

Edit:

This solution can handle arrays with any length in both dimensions but may require adjustments for more than two dimensions.

Answer №2

To maintain a list of unique values, you can utilize the Set method and then use array#reduce to generate an array containing only the unique items.

const arr = [['item 1', 'item 2'],['item 1', 'item 5'],['item 3', 'item 4'], ['item 6', 'item 5']],
      set = new Set(),
      result = arr.reduce((r, a) => {
        if(!set.has(a[0])){
          set.add(a[0]);
          r.push(a);
        }
        return r;
      },[]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

A simple technique to retain all items that do not meet a specific condition is by using the following method

arr.filter(item => item[0] !== arr[0][0])

It's important to be aware that this operation will also remove the first item from the array. In order to preserve it, you can store it separately before applying the filter.

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

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

Is there a way to exclude zeros when calculating the median for columns in an array?

I have a basic numpy array that needs some median calculations. array([[10, 0, 10, 0], [ 1, 1, 0, 0] [ 9, 9, 9, 0] [ 0, 10, 1, 0]]) My goal is to find the median of each column individually while ignoring any ' ...

Utilizing ng-model to control the visibility of a label or anchor tag

Here is the code snippet I am working with: <div class="tabs DeliveryRightDiv"> <label class="selected"><a>One</a></label> <label> <a>Two</a> </label> <label> ...

What is the best way to retrieve a variable in AngularJS1 after the HTML has been divided into multiple child HTML files?

I have segmented my main HTML page into multiple subpages and included them in the main file. However, it seems that each subpage is referencing different '$scope' variables. I am trying to reference ng-modle="My-model" from one subpage to anothe ...

Unleashing the power of real-time communication with XMPP using AngularJS

I am currently working on transitioning the basic XMPP setup using Strophe and JavaScript to AngularJS. .controller('loginCtrl', function(xmppAuth) { xmppAuth.auth(login, password); }) and in service: .service('xmppAuth', f ...

What is the best way to incorporate a dropdown menu into existing code without causing any disruption?

I've come across this question multiple times before, but I still haven't found a suitable answer or solution that matches my specific situation. (If you know of one, please share the link with me!) My goal is to create a basic dropdown menu wit ...

Is there a way to prevent pop-up windows from appearing when I click the arrow?

Is there a way to display a pop-up window when the green arrow is clicked and then hide it when the arrow is clicked again? I tried using the code below but the pop-up window disappears suddenly. How can I fix this issue using JavaScript only, without jQue ...

AngularJS views malfunctioning following oauth redirect

I am in the process of creating a web application using AngularJS and Firebase. Recently, I added a second page along with an ng-view to my index file. In order to facilitate login via Facebook or Google, I am utilizing the $firebaseAuth service. However, ...

Strategies for aligning the initial lines of text vertically within a table cell

I am faced with a unique challenge involving a table where the first cell contains the word "name" and the second cell contains some text. Sometimes, this text may include embedded images. The issue arises when an image appears on the first line of the tex ...

Refresh the Google Maps location using GPS coordinates

Currently, I am working with an Arduino that has a GPS chip and processing NMEA strings with Python. I have an HTML file set to auto-refresh every x seconds to update the marker's position. However, I would like to update the position information with ...

Arrow smoothly sliding beneath the selected tab in the active menu

Here is a reference picture. https://i.sstatic.net/wsp6R.png I am trying to create a slide effect for my arrow when clicking on different menu items. The arrow should move over the active menu item. By default, the arrow should point to the active menu. ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

Unusual outcomes stemming from JavaScript nested for loops

In my current project, I am working on verifying a submitted string against a set of letters. If the word_string is "GAR", the expected output should be "GAR" because all these letters are found in the letter set. However, I am facing an issue where some ...

Decipher intricate JSON with JavaScript

After retrieving a JSON object from Mongo DB, I have this data structure. **JSON** { "_id" : ObjectId("5265347d144bed4968a9629c"), "name" : "ttt", "features" : { "t" : { "visual_feature" : "t", "type_feature" : ...

How to retrieve values/keys from a JSON object dynamically in JavaScript without relying on fixed key names

shoppingCart = { "Items": 3, "Item": { "iPhone 11 Pro": { "productId": 788, "url": "http://website.com/phone_iphone11pro.html", "price": 999.99 }, "Bose Noise Cancelling Headphones": { ...

Angular - The connections between deeply nested object models are established

I have an Angular application that is used to display company and contact person information in a text box format. Here is the code for displaying the Company Email address: <label> Company Email address</label> <input type="text& ...

Ways to access information received from AngularJS in a different Javascript file

I am currently using Angular to retrieve output from a controller and display it using ng-bind. However, I have another separate JavaScript file that needs to utilize a value returned from Angular. In the example code provided below, the TestAppCtrl is ca ...

What is causing the loss of context for 'this' in the latest Angular 1.5 components?

Encountering a strange issue with the new components. Previously, in version 1.4 directive, we had this block of code... (function () { 'use strict'; angular.module('app.board').directive('dcCb', dcClipboardCopy); funct ...

Implementing a 1-second delay in a Vue.js delete request

I have items that are retrieved through API calls and users can add them to their cart. They also have the option to delete items from the cart, but I want the item to be visually removed from the front-end after 1 second because of an animation on the del ...

Combining ApolloProvider and StatsigProvider in ReactJs: A Step-by-Step Guide

Currently in my React (Next.js) application, I am utilizing statsig-react to switch between mastergraphql endpoint URLs. However, I am encountering an issue when trying to connect statsig with Apollo. This is how my app.js file looks like: const apollo = ...