Get the shared elements from several arrays with JavaScript

Find the shared value of 12 from the given array

For example: If the input is as follows:

[ [12, 6],[12, 11, 9, 8, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1] ]

The expected Output should be :

[12]

Answer №1

You can easily achieve this by utilizing Array#reduce in combination with Array#filter and Array#includes.

var array = [[12, 6], [12, 11, 9, 8, 1], [12, 11, 9, 8, 6, 1], [12, 11, 9, 8, 6, 1], [12, 11, 9, 8, 6, 1]],
    result = array.reduce((a, b) => a.filter(c => b.includes(c)));

console.log(result);

Answer №2

The most straightforward method would be as outlined below:

Pseudocode:

commonArray = clone(allArrays[0])
for i in 1, length(allArrays) do:
    removeIfNotExists(initialArray, allArrays[i])

The function removeIfNotExists could have a logic similar to this:

removeIfNotExists(commonArray, checkArray):
    for(index in commonArray):
        if(commonArray[index] not in checkArray):
            delete commonArray[index]

The goal here is to eliminate any elements from the common array that are not found in the check array. By repeating this process n times, you will end up with commonArray containing elements that are present in all arrays.

Answer №3

To simplify the array and then employ the reduce method to determine the frequency of each element is a useful approach. Subsequently, iterate through the resulting object to update the variable with the element that appears most frequently.

var arr = [
  [12, 6],
  [12, 11, 9, 8, 1],
  [12, 11, 9, 8, 6, 1],
  [12, 11, 9, 8, 6, 1],
  [12, 11, 9, 8, 6, 1]
]

// Flatten the array and reduce it to a single object
var flatObj = [].concat.apply([], arr).reduce(function(obj, item) {
    obj[item] = obj[item] === undefined ? 1 : obj[item] + 1;
    return obj;
  }, Object.create(null)),
  highestCount = 0,
  numWithHighestCount, key;
  
// Iterate over the new object created
for (key in flatObj) {
  // Update the variable with the highest occurring value
  if (flatObj[key] > highestCount) {
    highestCount = flatObj[key];
    numWithHighestCount = key;
  }
}
console.log([Number(numWithHighestCount)]);

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 transmit a response using JSON instead of Jade?

//This is the code in my index.js file var express = require('express'); var router = express.Router(); /* Display the home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Movie Datab ...

Tips for extracting HTML tags directly from JSON data

In my dataset, I have a JSON illustration [{ "Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n< ...

What is the best way to include a JavaScript function within a JSON file?

I am attempting to transform a JSON file into an object within my application, complete with embedded functions. However, I am facing difficulties in accomplishing this task. The JSON file causing issues is as follows: { "draw": function() { ctx.cle ...

the hidden input's value is null

I am encountering an issue with a hidden input in this form. When I submit the form to my API, the value of the input is empty. Isbn and packId are both properties of a book model. However, for some reason, the value of packId is coming out as empty. & ...

The item on my list is barely visible, as the height of the list column is adjusted upon loading the page

In my footer, I have a list of links. When I click on the last item labeled "See more links," jQuery's slideToggle() function replaces the list with new members. However, this action causes the bottom of my footer to shift slightly up and then back d ...

Troubleshoot the pattern of Pascal's Triangle

Can someone help me understand what's wrong with my implementation of Pascal's Triangle in JavaScript? I came across a similar thread discussing recursion, but I'm having trouble figuring out the errors in my code. I would appreciate fresh e ...

What techniques can be used to avoid blinking while forcefully scrolling to the left?

In my previous inquiry about dynamically adding and removing divs on scroll, I was unable to find a satisfactory solution among the responses provided. However, I decided to take matters into my own hands and attempted to implement it myself. My approach ...

What is the process for eliminating the invocation of a function in Jquery?

I am currently facing an issue with my application. When I launch the Ficha() function, it initiates an ajax call and works perfectly fine. However, another ajax call is made later to load HTML tags that also need to invoke the Ficha() function. The prob ...

Is there a way to store session variables in Angular without the need to make an API call?

I am currently working with a backend in PHP Laravel 5.4, and I am looking for a way to access my session variables in my Angular/Ionic project similar to how I do it in my Blade files using $_SESSION['variable_name']. So far, I have not discove ...

Blend pictures using jQuery

Hello, I am currently working on implementing a crossfade effect for the banner images on my homepage using jQuery. The fading effect is functioning correctly with the following code: <script> function bannerImages(){ var $active = $('.banne ...

How can Node.js handle an upgrade request effectively?

Dealing with a websocket 'upgrade' event from a Node.js http server presents an interesting challenge - The upgrade handler takes the form of function(req, socket, head) - Is there a method to respond to this upgrade request without access to a r ...

Switching between two states of a single 'td' element within a column

I am trying to implement a feature where only specific elements in the fourth column of a four-column table toggle when clicked. For example, clicking on an element in the fifth row third column should toggle the corresponding element in the fifth row four ...

Sending parameters to a function within the ngAfterViewInit() lifecycle method in Angular version 6

As a beginner in coding, I have created a canvas in Angular and am attempting to pass data received from my server to a function within ngAfterViewInit(). When I hard code the values I want to pass, everything works perfectly. However, if I try to pass da ...

Is there a way to create a customized calendar in Node.js?

I am looking for a way to showcase a calendar in a localized format, not only in terms of language but also supporting non-Gregorian calendars such as Persian, Chinese, or Buddhist. In the past, when I worked with Java, I relied on ICU4J for this task. Ho ...

Tips for labeling subplots in PLOTLY JS

Looking for some guidance on adding titles to plots in Plotly JS. I've checked out the documentation but couldn't find anything helpful. Any tips or suggestions would be greatly appreciated! ...

Utilizing asynchronous false in Wordpress Ajax functionality

Is there a way to use the AJAX return value outside the function in WordPress? For example: function get_login_member($) { $.post(ajax_object.ajax_url, {action: 'getloginmember'}, function (data) { data = JSON.parse(data); ...

How can you turn off CSS3 animations for browsers that don't support them

Upon page load, a fade-in animation is applied to the main container. Although it functions properly in most browsers, it seems to have an issue in IE(9). Is there a method to identify if the user's browser does not support CSS3 animations and disabl ...

Unable to store a customized class object in Parse database

I have been attempting to create a Customer class object that is linked one-to-one with the User class. However, despite my efforts, the object does not save and no error message appears. Here is the code I am working with: Parse.Cloud.afterSave(Parse.Us ...

What is the way to display the final list item when clicking in jQuery?

I am attempting to achieve a specific behavior where clicking on a button will trigger the content below to scroll in such a way that only the last item in the list is visible. I have been using jQuery for this functionality, but unfortunately, it is not ...

Is there a method to update the res object following a couchbase DB call without encountering the error "Error: Can't set headers after they are sent"?

let express = require('express'); let searchRoute = express.Router(); searchRoute.get('/', function(req, res, next) { console.log('1'); databaseCall(function(error, result) { if (error) { res.sta ...