Combining several arrays to find the array of shared elements as the final result

In my JavaScript/TypeScript application built with Angular, I am facing the challenge of merging multiple arrays and extracting the common values that appear in all arrays. For example:

arrayOne = [34, 23, 80, 93, 48]
arrayTwo = [48, 29, 10, 79, 23]
arrayThree = [23, 89, 48, 20, 63]

The desired output should be: outputArr= [23, 48]

To achieve this for two arrays, I am using a filtering method where I filter one array based on the elements present in the other array.

return this.arrayOne.filter(el => this.arrayTwo.includes(el));

However, I am now seeking an efficient way to handle a large number of arrays while still obtaining the common elements. Any suggestions or advice on how to tackle this effectively would be highly appreciated. Thank you in advance!

Answer №1

If you want to efficiently find common values across multiple arrays, consider utilizing a series of Set objects to streamline the search process.

const intersection = <T>(arrays: T[][]): T[] => {
    if (arrays.length == 0) return [];
    if (arrays.length == 1) return arrays[0];

    const sets = arrays.slice(1).map(array => new Set(array));

    const result = [];

    arrays[0].forEach(item => {
        if (sets.every(set => set.has(item))) {
            result.push(item);
        }
    });

    return result;
};

const arrayOne = [34, 23, 80, 93, 48];
const arrayTwo = [48, 29, 10, 79, 23];
const arrayThree = [23, 89, 48, 20, 63];

const result = intersection([arrayOne, arrayTwo, arrayThree]);

console.log(result);

Answer №2

To find common elements among multiple arrays, one method is to start with an initial set containing the elements of the first array. Then iterate through the remaining arrays, converting them into sets and updating the initial set to keep only the elements found in all arrays.

const findCommonElements = function(arrays) {
    if (arrays.length == 0)
        return [];
    const intersection = new Set(arrays[0]);
    for (const array of arrays) {
        const set = new Set(array);
        for (x of intersection) {
            if (!set.has(x))
                intersection.delete(x);
        }
    }
    return Array.from(intersection);
};

If we apply this function to the example arrays provided:

findCommonElements([
    [34, 23, 80, 93, 48],
    [48, 29, 10, 79, 23],
    [23, 89, 48, 20, 63]])

The result will be:

[23, 48]

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

Typescript: Exploring the Assignability of Numbers, Strings, and More to Null

Why does TypeScript display errors only when assigning a string to a number, but not when assigning null to a number? export type ArrayWithNumberOrString = Array<number | string>; export type ArrayWithNumberOrNull = Array<number | null>; f ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

Tips for modifying the text color of a div that is being iterated through using ngFor

I am facing an issue with a div that is being looped using ngFor. What I want to achieve is when a user clicks on one of the divs in the loop, only that particular div should change its text color. If another div is clicked, it should change color while th ...

Using React-Bootstrap with TypeScript in your project

I'm currently working on creating a navigation bar using react-bootstrap. I've already installed the node-module as follows: "@types/react-bootstrap": "^0.32.11",. However, when I try to use it in my hello.tsx component, I encounter a compile err ...

Sending data using the x-www-form-urlencoded format from a Firebase cloud function

I'm attempting to send an API request to the Stripe API from a cloud firebase function using an HTTP POST method. The parameters required must be in a format known as 'x-www-form-urlencoded'. const httpOptions = { headers: new ...

Is it possible for object destructuring in Javascript to include dynamic non-rest keys using ...rest?

Suppose we have an object: const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" }; My goal is to filter out specific keys from this object to create a smaller one. I am aware of the following ...

Validation in Express. The property 'validatePassword' is not found within the type 'Document'

Recently, I started working with express and node.js to create an authentication system without a frontend. I am utilizing typescript, passport, passport-local, and mongoose in my project. However, I encountered the following errors: TSError: ⨯ Unable t ...

Reflecting vertically in an image using a byte array

I am working on creating a DataMatrix decoder in C# using the ZXing.NET library. While I have successfully coded a QR decoder with ZXing, I am encountering an issue with the DataMatrix decoder. It seems that in order to successfully decode the DataMatrix, ...

Utilizing Typescript with Vue 3's Injection Feature

Using the new Vue 3 Composition API, I have created a "store" for reactive data. const state = reactive<State>({ accessToken: undefined, user: undefined, }); export default { state: readonly(state), } When my app is created, I pass the store ...

Webpacker/Typescript is unable to locate a file within the Rails asset pipeline

I'm currently experiencing difficulty importing a file from the rails asset pipeline as webpack seems to be unable to locate it. Here is the content of my tsconfig.json: { "compilerOptions": { "declaration": false, "emitDecoratorMetadata": ...

My Java program is receiving unexpected zeros at the end of my arrays

When I output my array long pair[], I noticed that zeros are being added to empty slots. What could be causing this issue? Any assistance would be greatly appreciated. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { dif ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Uncovering the Issue with Select All Functionality in <Table/> when using Material-UI and React

When using Material-UI's <Table/> with ReactJS, a table is set up with a select all checkbox. Each time an individual row checkbox is clicked, the row id is added to the state array clickedRowIds. This allows for logging of the ids of the clicke ...

What methods are available to change one JSON format into another?

I am receiving JSON data from a Laravel API in the following format: [ { "id":48, "parentid":0, "title":"Item 1", "child_content":[ { "id":49, "parentid":48, "title":"Itema 1 ...

Update and send back variable on the spot

I'm interested in learning the syntax for creating an inline function that can accept a parameter, perform a simple modification on it, and return it all in a single line. Here's an example: (input) => { input.status = 'complete'; ...

Tips for accessing and modifying multi-dimensional arrays using key names or paths

I need to create a setter function in PHP that allows me to set a value in an array by specifying the key or sub-key as a dot-separated string. Consider the code snippet below: $arr = array('a' => 1, 'b' => array( ...

I am interested in organizing a three-dimensional array using JavaScript

Just the other day, I posted a question on PHP, but now I need similar help for JavaScript. Here is my array : var inboxMessages = { 105775: { 0: { 'id': 85, 'thread_id': 105775, ' ...

Exploring ways to list interface keys in order to create a new interface where the value is determined by the corresponding key

How can we iterate through interface keys to create a new interface where the value is dependent on the key? type IParse<T> = { [K in keyof T as K extends string ? K : never]: string // How can we specify that if K === 'a', the type sho ...

Issue with extraneous characters appearing during transformation from object to String using GSON

Looking to convert an array of objects into an array of strings using Google Gson? Check out this code snippet: TestFile.java public class TestFile { public String[] objectsToStrings(Object[] obj) { Gson gson = new Gson(); String[] converted = n ...

Where's the tsconfig.json for Firebase Emulators?

I've encountered an issue with my Firebase project that's written in JavaScript (not TypeScript). When attempting to run the functions emulator, I'm getting the following error: $ firebase emulators:start --only functions ⚠ functions: Ca ...