Tips for removing arrays and their values when a duplicate id is detected

Is there a way to remove or filter out subsequent arrays and their values if a duplicate id is found in the previous array? For instance:

const a1 = ["id1", "b", "c", "d", "e"],
      a2 = ["id2", "y", "z", "w", "v"],
      a3 = ["id3", "k", "j", "i", "f"],
      a4 = ["m", "n", "o", "p", "id2"],
      a5 = [1, 2, "id1", 3, 4]

If an id1 is present in a5 and id2 in a4, the arrays containing these duplicate id should be removed or filtered out, keeping only the first occurrence of each unique id. Therefore, the expected output for the above example would be:

           [
            ["id1", "b", "c", "d", "e"],
            ["id2", "y", "z", "w", "v"],
            ["id3", "k", "j", "i", "f"]
           ]
      

Answer №1

One method to filter arrays within an array is to utilize an object as a hash table.

const
    data = [["id1", "b", "c", "d", "e"], ["id2", "y", "z", "w", "v"], ["id3", "k", "j", "i", "f"], ["m", "n", "o", "p", "id2"], [1, 2, "id1", 3, 4]],
    seen = {},
    result = data.filter(a => {
        const id = a.find(v => v.toString().startsWith('id'));
        if (seen[id]) return;
        return seen[id] = true;
    });

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Conducting simultaneous tests on the mobile application and web browser to ensure optimal performance

Dear friends, I am in need of some assistance. I am looking to run end-to-end tests simultaneously on a mobile app and a web browser, make alterations on one platform, and check to see the changes reflected on the other multiple times. My current plan is t ...

I'm having trouble getting this angular expression to cooperate in Plunker. Can anyone shed some light on why {{ 843 / 42

I'm currently diving into Angular with the help of Plural Sight. The initial lesson dives into utilizing the ng-app directive. For those interested, here's a direct link to the Plunker editor: http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview ...

Maintaining microsecond accuracy when transferring datetime values between Django and JavaScript

It appears that django, or the sqlite database, is saving datetimes with microsecond precision. However, when it comes to transferring a time to javascript, the Date object only works with milliseconds: var stringFromDjango = "2015-08-01 01:24:58.520124+1 ...

Executing a callback function in AngularJS after dynamically rendering elements with `ng-repeat`

Many posts demonstrate how to implement callback functions in directives to wait for ng-repeat to finish before calling a function. Here is an example: <div ng-repeat="Object in Objects" class="objectClass" on-finish-render>{{Object.Overlay}</div ...

How can a chat script be created efficiently without needing Server Root Access?

I currently have a hosting account (cPanel or DirectAdmin) where I don't have root access and am unable to use exec() or shell_exec() functions due to restrictions set by the server administrator. While I understand that socket programming is conside ...

Creating stunning visuals with the power of SVG

I need to create a graphics editor similar to Paint using SVG for a school project. I have JavaScript code for drawing shapes like circles and lines, but when I try to add them to an onClick function for a button, it doesn't seem to be working. funct ...

A PHP array containing various values assigned to specific indexes

I am looking to create an array or function in PHP that works as follows: - For indexes between 1-20, the output should be "type 1" - For indexes between 20-25, the output should be "type 2" - For indexes between 25-35, the output should be "type 1" ...

OpenLayers' circular frames surrounding the icons

I am currently using openlayers and trying to implement a feature that creates a circle around the icons on the map. I have been referring to this example on Stack Overflow but unable to draw the circle successfully. Can someone please assist me with this? ...

Utilize Ant Design TreeSelect to seamlessly integrate API data into its title and value parameters

I am currently working on populating a Tree Select component in ANT Design with data fetched from an API. The response from the API follows this structure: projectData = ProjectData[]; export type ProjectData = { key?: number; projectId: number; ...

Conditional statement in Javascript for document.cookie

I am attempting to create a basic if statement that relies on the value of a cookie. The function looks like this: function setHomePage() { if ($.cookie('settingOne') == 'jjj') { $('.secO').css('display', & ...

What method does jQuery 2.x use to distinguish one element from another in the .data() function?

Back in the days of jQuery 1.x, elements would be assigned a unique identifier known as a cache key, stored in the ele[jQuery.expando] property of a node set by a specific line of code. This caching mechanism has similarities with how Mootools handles its ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

The JavaScript function String.split() is generating an array filled with 20 empty strings

Attempting to replicate the functionality of jQuery's string-based HTML element determination, I employed a split function. However, rather than returning a list of values as intended, it produced an array containing twenty empty strings. console.l ...

What is the best way to handle query string parameters when routing in Next.js?

One of the challenges I am facing is related to a URL structure like this: bar?id=foo When I navigate to this URL using router.push('bar?id=foo'), everything works perfectly. However, if I directly access the route in the browser, the query st ...

execute function following ng-repeat

I'm diving into Angular for the first time and I want to start with a simple example. After using ng-repeat to display some data, I'd like to manipulate that data with JavaScript functions. However, I'm not sure when to trigger the JavaScri ...

Failing to retrieve data from Ajax response

When handling requests in a servlet, the following code snippet processes the request received: Gson gson = new Gson(); JsonObject myObj = new JsonObject(); LoginBean loginInfo = getInfo(userId,userPwd); JsonElement loginObj = gson.toJsonTree(loginInfo) ...

Is it possible to utilize WebRTC (simple-peer) with STUN without the need for additional signaling?

I am currently exploring the utilization of the simple-peer library to create browser-to-browser WebRTC connections through data channels. My understanding, although it may be flawed, is that for two browsers to establish a connection via WebRTC, they need ...

JQuery, Draggable delete

I created a shopping cart with drag-and-drop functionality for nodes. http://jsfiddle.net/dkonline/Tw46Y/ Currently, once an item is dropped into the bucket (slot), it cannot be removed. I'm looking to add that feature where items can be removed from ...

Can React provide custom styling to a specific segment of text before displaying it?

I'm looking to create a pokemon search box that offers suggestions of pokemons as the user types. It's working fine so far, but I also want to highlight the searched text when displaying the entire pokemon name. Basically, I want to replace the ...

Tips for swapping a component with another component in React.js without the need for a page refresh

class Navigation extends Component { constructor(props) { super(props); this.state = { width: window.innerWidth, } } updateWidth = () => { if (this.state.width > 700) { this.setStat ...