Tips for finding the common elements in arrays within a nested array

I am facing a challenge with an array that was generated by another function and I don't want to make any modifications to it.

var d = [[1, 2, 3], [2, 3], [1, 3]];

My goal is to use the _.intersection method on all arrays within the main array like this:

var c = _.intersection(d);
// expecting to get [3]

However, the _.intersection method requires multiple array parameters as input, not an array of arrays.

I attempted to flatten the array using a similar approach mentioned in Merge/flatten an array of arrays in JavaScript?, but it flattened the entire array into one single array.

var merged = [].concat.apply([], d);    
[1, 2, 3, 2, 3, 1, 3]; // This is not what I want 

To provide more context, I have a nested array d (which contains arrays and its length varies). My aim is to find the intersection of all arrays within the array d.

Is there a way for me to dynamically call

_.intersection([1, 2, 3], [2, 3], [1, 3], ...)
based on the contents of array d?

Answer №1

If you're working with ES5, one way to spread the array into parameters is by using Function#apply:

var d = [[1, 2, 3], [2, 3], [1, 3]];

var result = _.intersection.apply(_, d);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

For those using lodash, you can utilize _.spread which converts a function to accept an array of parameters:

var d = [[1, 2, 3], [2, 3], [1, 3]];

var result = _.spread(_.intersection)(d);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

As for ES6 users, the spread syntax provides a concise way to achieve the same outcome:

const d = [[1, 2, 3], [2, 3], [1, 3]];

const result = _.intersection(...d);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Answer №2

The result you are looking for is not a standard data structure in JavaScript, but you can achieve it by deconstructing the arrays into variables:

let [a,b,c] = [[1, 2, 3], [2, 3], [1, 3]];
console.log(a,b,c);

If you specifically need the desired output as a string, you can do so with the following function:

let d = [
  [1, 2, 3],
  [2, 3],
  [1, 3]
];

function createString(arr) {
  let s = arr.map(el => `[${el}]`).join(", ");
  return `result ${s};`;
}

console.log(createString(d));

Answer №3

If you want to access each internal array separately, the best approach is to assign them to individual variables. In ES6, you can easily achieve this by doing:

let d = [[1, 2, 3], [2, 3], [1, 3]];
let [arr1, arr2, arr3] = d;
// -> arr1: [1, 2, 3], arr2: [2, 3], arr3: [1, 3]

Alternatively, you can use the traditional ES5 syntax to accomplish the same task.

If you wish to work with all the internal arrays using a single variable, your only option is to utilize the parent array d.

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

Adding an item to a sleek carousel

Adding items to a Slick carousel in a vue.js demo is proving to be a bit tricky. When I try to use the refresh() function after adding an item, it doesn't seem to work as expected even though the item is successfully added with vue.js. //Attempting to ...

What is the process for activating namespacing on a VueX module that has been imported?

I am currently utilizing a helper file to import VueX modules: const requireModule = require.context('.', false, /\.store\.js$/) const modules = {} requireModule.keys().forEach(filename => { const moduleName = filename ...

How can you utilize jQuery's .post() method to send information as an object?

When I send a .post() request like this var data = $(this).serialize(); $('form').on('submit', function(event) { event.preventDefault(); $.post('server.php', data, function(data) { $('#data').append( ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

EJS forEach method not displaying output

Trying to work with this .ejs file that's supposed to loop through an object and retrieve data from an API. However, after fetching the data, it appears that nothing is being displayed on the screen. I've checked the API results in the console l ...

Configuring a Meteor.js application requires defining variable scopes for templates in order to manage

Is there a way to define a variable that is limited in scope to a specific template? I want this variable to be accessible by multiple helpers within the template, but not outside of it. For example, how can the game variable be shared between two templat ...

Exploring the world of AngularJS with nested JSON structures and utilizing ng-repeat

While going through code left behind by a previous team member, I find myself navigating the transition to Angular solo, without anyone around to brainstorm with. This brings me to my question for the community. I am working with JSON data that contains t ...

Utilize debounce functionality for custom filtering in a Vuetify data table

I am looking to enhance my search functionality by implementing a debounce method that would pause the search action after each keystroke for 1 second. However, even after implementing it, the search still occurs with every keystroke instead of waiting for ...

What is the best way to implement React Router within an if/else statement inside a function triggered by a button click?

const handleStartClick = () => { const userEmail = localStorage.getItem('email') if (userEmail !== null && userEmail.length !== 0) { alert('The email is not empty!') } else { <Routes> ...

Is there a way to verify if all the values in an array of objects are identical?

In this scenario, my array consists of entries with identical address IDs but different phone types and numbers. I am in need of assistance with iterating through the array to extract the phone type and number when the address ID matches. I seem to encount ...

Implementing Text Box Control Validation within a Gridview using UpdatePanel in c# ASP.Net

In my gridview, one of the columns contains a Text Box Control. I am looking to validate the text entered by users as alphanumeric characters and spaces only. Allowed characters are: a-z, A-Z, 0-9, and space. I want to perform this validation using Java ...

Tips for resolving the Angular Firebase v.7 problem: The search for '_delegate' in the users/xxxxx cannot be conducted using the 'in' operator

I'm working on implementing the new Angular Firebase v.7 with Angular and encountering an error message: Cannot use 'in' operator to search for '_delegate' in users/1QAvZYg6aqe0GhA13tmVAINa. While I found a similar question ( Fire ...

preserving a photo that has been edited using caman.js

Hey everyone, I've been working on this for a few days and I could really use some help. I used camanjs to manipulate an image and then saved it to disk using canvas.toblob(). Here's the code: Caman("#theCanvas", "images/1.jpg", function () { ...

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

Utilize Redux in conjunction with TypeScript to seamlessly incorporate a logout feature

My login page redirects to a private /panel page upon successful login with an accessToken. I am utilizing the Redux store to verify the token in the privateRoute component. Challenges I'm encountering: I aim to enable logout functionality from t ...

Waiting for the code to execute once the filtering process is completed in Next.js using Javascript

I'm seeking a way to ensure that my code waits for the completion of my filter function before proceeding. The issue arises because my filter function, which incorporates another function called useLocalCompare, causes a delay in execution. This delay ...

Creating a table with a static first column and vertical text positioned to the left of the fixed column

To create a table with the first column fixed, refer to this fiddle link: http://jsfiddle.net/Yw679/6/. You also need a vertical text to be positioned to the left of the fixed column in a way that it remains fixed like the first column. The disparities be ...

Traverse each array within the array and transmit the coordinates to Google Maps

I'm working on a Rails app that includes a Google map displaying pins based on coordinates (latitude, longitude). I've set up some dummy data in the user.rb file as an array and am trying to iterate through it to pass the coordinates to the Googl ...

What is the best method for removing a class with JavaScript?

I have a situation where I need to remove the "inactive" class from a div when it is clicked. I have tried various solutions, but none seem to work. Below is an example of my HTML code with multiple divs: <ul class="job-tile"> <li><div ...

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...