Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this:

const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']

The goal here is to subtract the elements in array A from array B. The expected result should be:

const result = ['Mo', 'Mo', 'Sa']

What is the best way to achieve this task? It may seem straightforward, but I'm having trouble making it work.

Essentially, the desired outcome is to remove all elements from B that are also present in A.

Answer №1

const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']

console.log(A.reduce((b, a)=>
  (b.includes(a) && b.splice(b.indexOf(a),1), b), [...B]))

Providing the solution without utilizing code golf:

const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr']
const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa']

console.log(A.reduce((b, a)=> {
  if(b.includes(a)) b.splice(b.indexOf(a), 1); return b; }, [...B]))

Answer №2

An amusing little twist on filtering a map of A.

const A = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
const B = ['Mon', 'Mon', 'Mon', 'Tue', 'Thu', 'Fri', 'Sat']

const aMap = A.reduce((accumulator, current) => (accumulator[current] = (accumulator[current] ?? 0) + 1, accumulator), {})
const result = B.filter(item => !(aMap[item]-- > 0))

console.log(result)

Answer №3

def check_days_in_week(day1, day2):
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    
    if day1 in days and day2 in days:
        return True
    else:
        return False

Answer №4

Give this a shot:

const X = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
const Y = ['Jan', 'Feb', 'Mar', 'Mar', 'Apr', 'May', 'Jun']
let result = Y;
X.forEach(value => {
  for(let index = 0; index < result.length; index++) {
    if(result[index] === value) {
      result.splice(result.indexOf(value), 1);
      break;
    }
  }
});

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

Transfer the values from identical textboxes to jQuery, and subsequently to a PHP page for saving them to a database

Here is a list of textboxes that I have: ` <table id="div1" style="width:100%;"> <tr> <td> <label>Question Text</label> </td> <td colspan="5"> ...

The form response values consistently show as undefined, attempting to send them to the backend with no success so far after trying two different approaches

I've tried approaching this issue in two different ways, but both times I end up with a value of "undefined" instead of the user input from the form. Just to give some context, I'm using material UI forms for this project. The first approach inv ...

Using PHP's for loop to iterate through data and store them into arrays

Attempting to transmit data from JavaScript to a PHP file through an AJAX request, and then store each result in an array using PHP. queryData={"data":{"data_string":{"data":"medicine","default_field":"Content"}}} testArgument=0; $.ajax({ url:"test/q ...

resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON. However, when trying to close the new Promise function, I want the resolve function to return the ...

Error encountered when utilizing Meteor in conjunction with TypeScript

Currently, I am in the process of building a web application using Meteor and TypeScript within the Nitrous.io cloud development environment. After installing the TypeScript compiler, I integrated TypeScript libraries from https://github.com/meteor-typesc ...

Is there an easy method for sorting through JSON data with various criteria?

After receiving a response from my web service containing an array of objects, I am looking to filter the data based on various combinations of values. What is the most efficient way to do this without impacting the performance of my web service? Data: Th ...

Is memory allocated for 32 bits for variables with an undefined value in Javascript?

If I have a function with the signature below: function test(variable1, variable2) {} And I call it with only one parameter: test(5); Then within the test function, variable2 will be created but with a value of undefined. I'm interested to know if ...

Step-by-step guide on making a duplicate of a Search bar

I have a search field in my application that I want to duplicate. The goal is to create two identical search fields, one on the left side of the page and another on the right side. How can I achieve this using JavaScript? Here is my JavaScript code: doc ...

Ways to automatically change a URL into a clickable link upon pasting

When attempting to paste a URL into the text box such as https://stackoverflow.com/, it does not automatically convert to a hyperlink. I previously tried using regular expressions in this related question. The function I implemented worked correctly, howe ...

Initiate an Ajax call to pre-fetch video content

I've been attempting to download a video from my own source and display a loading message while it's being downloaded. Once the download is complete, I want to hide the loading icon and have the video ready for playback. My issue lies in gettin ...

How can I use AJAX to update a DIV when an image is swapped out?

I run an online radio station and I've been looking for a way to display album artwork for each song that plays. After setting up the ability to automatically upload the image of the currently playing song as "artwork.png" to a web server via FTP, I c ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

Looking for nested objects within an array in JavaScript

Currently, I am dealing with a REST API that provides data in the following format: students = [{ batch_id: 22 id: 1 image: null name: "a new batch student", attendance: [ { id: 1, student_id: 1, batch_id: 22, absent_on: "2019-09-15", ti ...

Issues with Mega Menu functionality preventing items from being clickable and links from properly navigating

Recently, I encountered a strange issue related to the integration of a mega menu found at . Unfortunately, despite integrating the mega menu, the Category and sub category links seem unresponsive - they are not directing me to the desired links. I suspec ...

Node.js exec command encountering an uninformative error message and not executing properly

Here is the snippet of code that needs to be executed cp.exec("cc -Wall /tmp/test.c -o /tmp/test", function(e, stdout, stderr) { if (e) { var errorstr = "There was an error during compilation: "+ e.message.toString() ...

Is there a solution for the continuous automatic incrementing of the jQuery UI spinner that occurs when I right-click on it?

Only Linux and Mac OS users are facing this particular issue, indicating a potential bug with the jQuery spinner. The bug also affects the spinner located at the following link: https://jqueryui.com/spinner/ <input class="spinner"/> $(".spinner"). ...

Assign a value to an object within a Vue data property

Hey there, I am currently learning vuejs and facing an issue with setting an object value to a vue data property. data: () => ({ newTodo: "", todoObj: { title: newTodo, undo: false }, toDoList: [ { title: "Study", undo: false }, ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...

Preventing form submission with JavaScript by implementing multiple validation checks

Preventing a form from submitting when validation returns false is possible. Here's an example: <form name="registration" action="registration.php" onsubmit="return validate()"> <!-- some inputs like: --> <input type="text" id="us ...

How come this variable isn't recognized as 0 even though the debugger is indicating otherwise?

I am currently working on a React component that receives the total number of reviews as a prop. In cases where the number of reviews is 0, I intend to display an element indicating <div>No reviews yet.</div> If there are reviews available, I ...