What is the best method for combining multiple arrays of objects without any duplicate elements?

I have been trying to solve this issue, but all the solutions I found assume that you know the number of arrays you want to merge without duplicates.

My task is to iterate over an object containing multiple arrays. Each array holds objects structured as follows:

{sType: string, nLaId: number, sname: string}
. To determine if an object is a duplicate, I need to compare it with other objects based on both sType and nLaId.

for(let key in objectContainingArrays){
  // How can I efficiently merge these arrays without duplicating any objects?
}

If there is a straightforward solution or if this question has already been answered elsewhere, I apologize and would be grateful for a link. Thank you!

Answer №1

If you're not utilizing any libraries such as underscore.js, one way to handle arrays is by first merging them and then removing any duplicates:

var mergedArray = [].concat.apply([], arrList);

var uniqueArray = mergedArray.filter((currentValue, index, arr) => 
  arr.findIndex (
     arrItem => (
        arrItem.sType === currentValue.sType && arrItem.nLaId === currentValue.nLaId)
     ) === index
);

Here's a sample scenario -

var arr1 = [{
    sType: "S1",
    nLaId: 1,
    sname: "N1"
  },
  {
    sType: "S2",
    nLaId: 2,
    sname: "N2"
  },
  {
    sType: "S3",
    nLaId: 3,
    sname: "N3"
  }
];
var arr2 = [{
    sType: "S2",
    nLaId: 2,
    sname: "N4"
  },
  {
    sType: "S2",
    nLaId: 2,
    sname: "N5"
  },
  {
    sType: "S1",
    nLaId: 3,
    sname: "N6"
  },
  {
    sType: "S4",
    nLaId: 3,
    sname: "N7"
  }
];
var arr3 = [{
    sType: "S1",
    nLaId: 1,
    sname: "N8"
  },
  {
    sType: "S2",
    nLaId: 2,
    sname: "N9"
  }
];

var arrList = [arr1, arr2, arr3];
var mergedArray = [].concat.apply([], arrList);
var uniqueArray = mergedArray.filter((currentValue, index, arr) => 
arr.findIndex(arrItem => (arrItem.sType === currentValue.sType && arrItem.nLaId === currentValue.nLaId)) === index);

console.log(uniqueArray);

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

CFGRID Binding Issue: Element Not Located in CF11 Compared to CF2018

After spending some time tinkering with this issue, I finally found a solution that worked for me. I decided to share it here in the hopes that it might help others save some time. In ColdFusion 11, my binding parameter looked like this: <cfset args.b ...

Ways to update div content following a successful AJAX call

I have a form that utilizes AJAX requests, and when the input fields are not filled correctly and the submit button is clicked, error messages are displayed without refreshing the page. While this functionality works, a problem arises when the form is subm ...

Discovering the size of an attribute in an object using Angular

I am working with a JSON object named "programs" that contains an array of key/value pairs. My task is to determine the count of objects within this array that have the key/value pair "status": "Review". In this case, there are 4 objects in total and 2 o ...

Error TS2532 in Typescript is indicating that an object may potentially be undefined, despite the fact that I have applied necessary checks

Can anyone help me with this strange issue I'm experiencing in Typescript? I keep getting an error about a potential undefined value: https://i.sstatic.net/GaLv7.png if (!flatListRef || !flatListRef.current) return flatListRef.current.someMethod() ...

Does anyone know how to retrieve the application version or import the package.json file? Can't seem to find the solution on

I need to display the version from the package.json file in my Angular application. To import it, I allowed importing json by adding a few extra lines in tsconfig.json: { "compilerOptions": { "module": "commonjs", ...

Adding an error or validation message to the renderer within a React hook - a quick and easy guide

{ label: "Room", name: "room", type: "select", rule: yup.string().required(), renderer: (data: any) => { const { control, register, errors } = useFormContext(); return ( <SelectPicker plac ...

What is the method to create all possible combinations from the keys of a JSON object?

How can I generate object B that includes all combinations of object A using a key-value pair? { "x": "data-x", "y": "data-y", "z": "data-z" } The desired output should look like this: { ...

Upon page reload in Nuxt.js middleware, Firebase authentication is returning as null

Just started with nuxtjs and using the Nuxt firebase library for firebase integration. After a successful login, I'm redirecting the user to the "/member/desk" route. However, if I refresh the page on that particular route, it redirects me back to "/a ...

Using Try...catch compared to .catch

Within my service.ts file, I have various user service functions that handle database operations. export const service = { async getAll(): Promise<User[]> { try { const result = await query return result } catch (e) { rep ...

Update an item's precise orientation in relation to the global axis

Update: Included a jsfiddle for clarification: JSFiddle I am working with an object (a cube) in a scene and my objective is to provide it with 3 angles that represent its orientation in the real world. These angles are measured against the X, Y, and Z ax ...

The iframe is being loaded in the center of the page rather than at the top

I am currently facing an issue with embedding wetransfer into a website using iframe. The problem is that when the page loads, it automatically scrolls past the header section of the site instead of loading the new page at the top. How can I prevent this ...

Guide for dynamically populating Jqgrid Dropdown depending on another dropdown's data选择如何根

On my screen, I have two dropdowns. One is a standard Razor dropdown and the other is a Jqgrid dropdown. The code for the Razor dropdown looks like this: <div class="col-md-4"> <label for="" class="control-label">Loan Currency</ ...

Configuring the port number of the socketio connection in Heroku

I attempted to create a chat application using JavaScript and npm. After completing it to some extent, I deployed it to Heroku and encountered the error net :: ERR_CONNECTION_REFUSED in Chrome's developer tools. I suspect that Socket.io, Express, and ...

Tips for neatly wrapping a class constructor

Currently, I am experimenting with code to create a more streamlined Angular Dialog initializer. This initializer should be passed a constructor function along with its arguments in a type-safe manner. The current implementation works, but it is challengi ...

Exploring the concept of try-catch in JavaScript with a focus on the call stack within the Node

Recently, I delved into the world of Javascript and decided to explore how stack tracing functions in nodejs. Instead of looking at the source code, my lazy side led me to consult the language reference found at https://www.ecma-international.org/ecma-262/ ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

Understanding the mechanics of promises in Typescript amidst encountering a MySQL error

I am currently developing an application in Angular 8.3 with Node.js 10.17 and MySQL. When attempting to send JSON data to the Backend, I encountered an error with promises that I am struggling to resolve. I have conducted thorough research but still can ...

Collecting all Material-UI components into a single document

Currently, I am engaged in a Meteor project that utilizes Material UI and ReactJS. I wish to streamline the process by creating a single file that imports all necessary Material UI components for my project. This way, instead of adding individual exports ...

Ensure that any modifications made to an Angular service are reflected across all components that rely on that service

I am currently in the process of replicating a platform known as Kualitee.com, which serves as a test-management tool utilized by QA Engineers. Within Kualitee, users can access multiple projects, each containing various test cases and team members. The ab ...

Updating an array by adding or removing items

I am attempting to create a method for deleting and adding items to an array, but I need easy-to-use delete and add methods since I am unfamiliar with TypeScript. export class NgForComponent implements OnInit { Numbers: number[]; constructor() { ...