Eliminate duplicated partial objects within a nested array of objects in TypeScript/JavaScript

I'm dealing with a nested array of objects structured like this:

const nestedArray = [
   [{ id: 1 }, { id: 2 }, { id: 3 }],
   [{ id: 1 }, { id: 2 }],
   [{ id: 4 }, { id: 5 }, { id: 6 }],
]

In the case where objects with id 1 and 2 are already grouped together within the first element of nestedArray, my goal is to remove the second element while keeping all other elements unchanged. The desired outcome should be as follows:

const nestedArray = [
   [{ id: 1 }, { id: 2 }, { id: 3 }],
   [{ id: 4 }, { id: 5 }, { id: 6 }]
]

How can I implement a filter function based on the object's id to achieve this expected result?

Answer №1

Upon reviewing your example:

  1. The unique id values are present in each subarray
  2. Duplicate elements within sub-arrays only occur in the preceding sub-array
  3. If the initial element of a sub-array is found in the previous sub-array, then all subsequent elements must also be present

const nestedArr = 
  [ [ { id: 1} , { id: 2} , { id: 3} ] 
  , [ { id: 1} , { id: 2} ] 
  , [ { id: 4} , { id: 5} , { id: 6} ] 
  ] 

function cleanArray(arr)
  {
  for (let i=arr.length;i--;)
    {
    if (i>0 && arr[i-1].some(x=>x.id===arr[i][0].id) )
      arr.splice(i,1)
    }    
  }

cleanArray( nestedArr )

// outcome
console.log( 'nestedArr = [' )
nestedArr.forEach(e=>console.log('  ',JSON.stringify(e).replaceAll('"',''),','))
console.log('  ]')
.as-console-wrapper { max-height: 100% !important; top: 0; }
.as-console-row::after  { display:none !important; }

Answer №2

Give this a try:

const mixedArray = [
   [{ key: "A" }, { key: "B" }, { key: "C" }],
   [{ key: "A" }, { key: "D" }]
]

var freshArr = mixedArray.flat(2).filter((element, index, original) => index === original.findIndex((item) => (item.key === element.key)));
console.log(freshArr);

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 the best way to initiate a class constructor with certain parameters left out?

Currently, I am facing a challenge while trying to pass various combinations of arguments to a class constructor. The constructor has 2 optional arguments. Here is the code snippet: class MyClass { foo(a, b) { return new MyClass(a, b); } bar( ...

Creating a duplicate of a Flex object in HTML without the need to reinitialize

I'm currently developing a flash object that involves processing a large number of images. My goal is to load multiple flash objects on the same page in order to capture an image, make adjustments, and then display it within each flash object. Howeve ...

Utilize Sorting while Keeping the Original Keys

Is there another method I can use instead of the sort function in php that won't delete all the keys? ...

Run a JavaScript function in 5 seconds

I'm looking to execute this function after a 5-second delay: $(document).ready(function() { $("#signInButton").trigger('click'); }); Your assistance is greatly appreciated. ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

Guide on loading a PDF asset dynamically within an Angular application with the help of webpack

I am having trouble loading a PDF file into my Angular app, which is running on the webpack dev server. I am using the HTML <object> tag with the data attribute to achieve this. The issue arises because the PDF path is generated dynamically at runti ...

Is it possible to directly add a child in HTML from nodejs?

I'm in the process of developing a chat application that requires users to select a room from a list of available rooms stored in <datalist> options, which are fetched from a SQL table on the server. Within my login.html file, users are prompte ...

Troubleshooting issues with Vue CLI 4 and A-Frame: Finding solutions for

Recently, I've been working on creating a VR web app using Vue cli 4.2.3 and aframe.io. However, I encountered numerous error messages related to aframe's components. [Vue warn]: Unknown custom element: <a-scene> - did you register the com ...

The data does not seem to be getting sent by the res.send() method in

I'm having trouble with the GET request not returning the data I expect. Here is my GET request code: router.get('/', (req, res) => { res.set('Content-Type', 'text/html') res.status(200).send(Buffer.from('<p& ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...

Ways to display a jQuery alert when navigating on a webpage

I am looking to enhance my page navigation by implementing a jQuery confirmation message with 'Yes' and 'No' buttons. This way, when I navigate from one page to another, I can decide whether to proceed or stay on the current page. Inst ...

Error: The operation 'join' cannot be performed on an undefined value within Fast2sms

I am encountering issues while attempting to send SMS using fast2sms in Node.js. The error message reads as follows: TypeError: Cannot read property 'join' of undefined at Object.sendMessage (C:\Users\user\Desktop\node_module ...

Display only the initial outcome when using array_diff on an associative array

After realizing I forgot to ask the full question in a previous post, I'm glad I caught myself before asking the wrong one. So, here's the complete question: Array ( [idAsset] => 10000005 [AssetName] => HP ) Array ( [idAsset] => 1000000 ...

mysterious supplier factoryprovider <- factory <- angular js controller

I'm encountering an issue with injecting dependencies from a service to a controller. Despite adding it, I keep receiving the following error: Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl My main goal is to display ...

Can you explain the distinction in C++ between new and new[] when it comes to allocating arrays?

In my understanding, there is a difference in memory allocation and deallocation between C and C++. In C, malloc/free can handle both single objects and arrays seamlessly, while in C++, new/delete and new[]/delete[] pairs need to be used accordingly. Acco ...

While in the process of developing a React application, I have encountered the following challenge

PS F:\Programming Tutorials Videos\R Practice> npx create-react-app custom-hook npm ERR! code ENOTFOUND npm ERR! syscall getaddrinfo npm ERR! errno ENOTFOUND npm ERR! network request to https://registry.npmjs.org/create-react-app failed, reaso ...

What could be the reason my Virtual Mongoose categories aren't appearing?

Here is the description of my post model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PostSchema = new Schema({ text: String, image: String, author: { type: Schema.Types.ObjectId, ref: 'user&ap ...

The largest contentful paint is anticipating an unidentified event

My website is encountering issues with Google Pagespeed and I'm unsure of the cause. The primary bottleneck appears to be the LCP time, which Google reports as taking between 7 and 11 seconds during each test. Upon analyzing the waterfall chart, it ...

Incorporating AppLozic's chat plugin into an Angular 5 project

Struggling to incorporate a third-party chat plugin into my Angular 5 project. The documentation is proving difficult to understand, and I can't figure out how to proceed. If anyone has successfully integrated it before, your help would be greatly app ...

The login form constantly displaying the message "Incorrect Login Information"

<?php include 'header.php'; error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); $con = mysql_connect("localhost","root",""); $db_selected = mysql_select_db("layout",$con); $name = $_POST['name']; $password = $_POST['pass ...