eliminate shared elements across various arrays

I am working with 3 arrays (or potentially more or less) and my goal is to eliminate any common elements shared between them. For instance, in the first two arrays, the common elements are x and z, between the second and third array it's only t, and between the first and third array, it's just k. Essentially, I want to get rid of any duplicate elements that appear in multiple arrays.

!! Please note that the first array may also have common elements with the third one !!

This is what I have attempted so far, but it seems to be faltering:

let y = [{
    id: 'a',
    elems: ['x', 'y', 'z', 'k']
  },
  {
    id: 'b',
    elems: ['x', 't', 'u', 'i', 'z']
  },
  {
    id: 'c',
    elems: ['m', 'n', 'k', 'o', 't']
  },
]

// x, z, t

for (let i = 0; i < y.length - 1; i++) {
  let current = y[i].elems
  let current2 = y[i + 1].elems

  if (current[i] == current2[i]) {
    const index = current.indexOf(current[i]);
    if (index > -1) {
      current.splice(index, 1);
      current2.splice(index, 1);
    }
  }
}

console.log(y)

The expected outcome should look like this:

[
  {

    "id": "a",
    "elems": [
      "y"
    ]
  },
  {
    "id": "b",
    "elems": [
      "u",
      "i"
    ]
  },
  {
    "id": "c",
    "elems": [
      "m",
      "n",
      "o"
    ]
  }
]

What would be a correct and efficient solution for this? I have also tried combining all 3 arrays and removing duplicates, but then I struggle with splitting them back into separate arrays.. Any suggestions are welcome!

Answer №1

To start, I would iterate through all the elements and keep track of how many times each one has appeared. Then, I would loop through them again to remove any duplicates.

const myData = [{
    id: 'a',
    elems: ['x', 'y', 'z']
  },
  {
    id: 'b',
    elems: ['x', 't', 'u', 'i', 'z']
  },
  {
    id: 'c',
    elems: ['m', 'n', 'o', 't']
  },
]

// Counting occurrences of each element to identify duplicates
const allElems = myData.reduce((acc, item) => {
  item.elems.forEach( key => { 
    acc[key] = acc[key] || 0;
    acc[key]++;
  });
  return acc;
}, {})

// Filtering out elements that are not unique
myData.forEach(item => {
  item.elems = item.elems.filter(key => allElems[key] === 1);
})

console.log(myData)

Answer №2

let arr1 = ['apple', 'banana']
let arr2 = [{
    id: 'apple',
    items: ['red', 'yellow', 'green']
  },
  {
    id: 'banana',
    items: ['purple', 'orange', 'blue', 'green']
  }
]


// apple, green

for (let k = 0; k < arr2.length - 1; k++) {
  for (let l = 1; l < arr2.length; l++) {
    let curr = arr2[k].items
    let curr2 = arr2[l].items

    curr2.forEach((element, ind)=>{
      if(curr.includes(element)){
        curr.splice(curr.indexOf(element),1)
        curr2.splice(ind,1)
      }
    })
  }
}

console.log(arr2)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

const y = [
  { id: 'a', elems: ['x', 'y', 'z'] },
  { id: 'b', elems: ['x', 't', 'u', 'i', 'z'] },
  { id: 'c', elems: ['m', 'n', 'o', 't'] },
];

// counting occurrences of each element
const elems 
  = y.flatMap(e => e.elems).reduce((acc,elem) => { 
      acc[elem] = acc[elem] ? acc[elem]+1 : 1; 
      return acc;
    }, {});
      
// finding unique elements
const unique = Object.keys(elems).filter(elem => elems[elem]===1);

// removing non-unique elements from each item
const res = y.map(item => 
  ({ ...item, elems: item.elems.filter(e => unique.includes(e)) })
);

console.log(res);

Answer №4

Implementing a Map to tally occurrences after a single pass, then utilizing the map count for filtering final outcomes

let x = ['a', 'b']
let y = [{
    id: 'a',
    elems: ['x', 'y', 'z']
  },
  {
    id: 'b',
    elems: ['x', 't', 'u', 'i', 'z']
  },
  {
    id: 'c',
    elems: ['m', 'n', 'o', 't']
}]

const counts = new Map()
// first iteration to count values
y.forEach(({ elems }) => elems.forEach(v => counts.set(v, (counts.get(v) || 0) + 1)));
// second iteration to filter out dups 
y.forEach(e => e.elems = e.elems.filter(v => counts.get(v) === 1))

console.log(y)

Answer №5

Feel free to let me know if this solution meets your needs.

let y = [
  {
    id: "alpha",
    elements: ["apple", "banana", "cherry"],
  },
  {
    id: "bravo",
    elements: ["apple", "mango", "papaya", "kiwi", "cherry"],
  },
  {
    id: "charlie",
    elements: ["melon", "nectarine", "apple", "cherry", "mango"],
  },
];

// Iterate over each element in the first array
for (let e of y[0].elements) {

  // Check if this element is present in all other arrays
  if (y.every((obj) => obj.elements.includes(e))) {

    // Remove the element from all arrays
    for (let o of y) {
      o.elements = o.elements.filter((x) => x !== e);
    }
  }
}

Answer №6

let y = [{
    id: 'a',
    elems: ['x', 'y', 'z']
},
{
    id: 'b',
    elems: ['x', 't', 'u', 'i', 'z']
},
{
    id: 'c',
    elems: ['m', 'n', 'o', 't']
},
];
//

const checkIfElementExists = (element, array) => !array.find(el => el == element);
const mergeArraysExceptIndex = (index, array) => array.reduce((accumulator, currentValue, currentIndex) => currentIndex == index ? accumulator : [...accumulator, ...currentValue.elems], []);
const finalResult = y.map((line, index, array) => ({
    id: line.id,
    elems: line.elems.filter(value => checkIfElementExists(value, mergeArraysExceptIndex(index, array)))
}))

console.log(finalResult);

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

Encountering difficulties in the installation of the NODE-SCSS module

Encountering an error during the installation of the node-scss module with the following versions: npm version: 6.13.4 node version: v12.16.1 The error message indicates a failure at the postinstall script. Is this related to my node version? I attempted ...

Using JavaScript to divide an associative array into separate arrays

I am dealing with an array of clubs var clubs =[{ team: {name: "fcb barca", rank: 4}, team: {name: "man utd", rank: 16}, team: {name: "man city", rank: 36}, team: {name: "fcb liverpool", rank: 57} }]; The task at hand is to separate this ...

No value found for the existing property

Recently, I began working on building a RESTful API using node.js, express, and mongodb. The progress was smooth until now, where I encountered a problem with the authentication route for users: apiRoutes.post('/authenticate', function(req, res) ...

"Troubleshooting: Click counter in HTML/Javascript unable to function

My latest HTML project is inspired by the "cookie clicker" game, and I'm working on it for a friend. So far, I've managed to get the click counter to function to some extent. Essentially, when you click on the image, the number at the bottom sho ...

Utilize String to Set Cookies

My goal is to utilize requestjs for making requests and sharing cookies across various JavaScript files and servers. To achieve this, I have chosen to store the cookies in a database as a string and retrieve them when necessary. The string format aligns w ...

Looking for a JavaScript equivalent to Dart's millisecondsSinceEpoch functionality

A new chat system is being developed to connect mobile and web platforms using firestore. The challenge at hand involves the sorting of documents based on timestamp, as those created from both mobile (using flutter) and web (using vue js) are not in ascend ...

Straight pipe made with tubegeometry

Is it possible to create a straight tube using TubeGeometry? All the examples I find only show how to make curved tubes. ...

Triggering modal activation upon clicking on the SVG map

Seeking advice on the best way to implement a new feature. I have an SVG map with tiny blue icons that users can click on. You can refer to the image below for clarity: https://i.sstatic.net/XHry9.png Whenever a user clicks on any of these blue icons, I ...

I am curious to know why my jQuery when().then() function is firing before the completion of the ajax request in the when clause

I have a situation where I need to set an async callback because a function is fetching content from a remote location. Here's what I am currently doing: $.when( priv[box.view.renderWith](content, box.view.gadget_id) ).then(function(late) { conso ...

Setting the state to an array of objects in React: A beginner's guide

Currently, I am developing a flashcard application using React. To store the data entered by the user, I have initialized my state as an array of objects that can hold up to 10 terms and definitions at a time: state = { allTerms: [ { ...

What methods does Node use to manage multiple users simultaneously?

As I delve into learning Node.js, a question arises about how it handles multiple users. For instance, if two users send requests simultaneously, does Node create separate instances for each? Let's say I am storing the username in a variable called & ...

Streamline jQuery code for dynamically populating two select dropdowns

I am looking to streamline and enhance this script to make it more dynamic. There could be multiple items in options, potentially even up to ten items. In the current scenario, the maximum number of items allowed is 2. The total value selected across both ...

Troubleshooting JavaScript Integration in PHP Scripts

I'm currently working on creating an advertisement switcher that can display different ads based on whether the user is on mobile or desktop. I've tried inserting PHP includes directly into the code, and while it works fine, I'm struggling t ...

Managing a plethora of JavaScript scripts in Aptana Studio

Recently, I wrote a few lines of Javascript code using Aptana Studio 3 for a web project and decided to outsource some of it. Here is the original code structure: (function(window) { var App = { // properties and functions... }; App.SubObject1 = { // ...

Using JavaScript, verify if the user is connected to a network

Does anyone know of a simple method to verify if the user is able to access our website? Determine if they are not receiving a connection error. ...

Removing all repetitions from an array in JavaScript

My collection of objects includes the following inputs: var jsonArray1 = [{id:'1',name:'John'},{id:'2',name:'Smith'},{id:'3',name:'Adam'},{id:'1',name:'John'}] There is a dupl ...

Unable to retrieve information obtained from MongoDB

After successfully retrieving all data from the "topics" collection using find() with cursor and foreach, I am encountering an issue. When I attempt to assign the fetched information to a variable named "data" and send it back to the page, it consistently ...

Check the number of rows in MySQL and if it is equal to 0,

I am working on developing a function to detect locations within a specific distance from a waypoint. The distance calculation function is already functional, and I have initiated the process with the query displayed below. select loc_id from wp where calc ...

Tips for recalling recently visited items

I've been testing out this code that checks the self-address. This means that if we are in /_test.php?id=45, the code will run. The code is located in header.php, which is included on every site. if ( $srv == '/_test.php') { $aid = $ ...

Align elements horizontally

Currently, I am developing a blog application using React, Material UI, and Tailwindcss. One issue I am facing is that each postcard in the grid has a different height, and I want all cards to have the same height while keeping all children aligned in the ...