Ternary conditionals don't support splicing

Seeking a solution to eliminate any duplicate numbers from two arrays:

function removeDuplicates(args) {

  var uniqueNumbers = [].concat.apply([],arguments).reduce(
    function(result, current) {

      console.log("result: " + result);
      console.log("current: " + current);
      console.log("result.indexOf(current): " + result.indexOf(current));

      return result.indexOf(current) === -1 
      ? result.concat(current) 
      : result.splice(result.indexOf(current), 1);
    }, []
  );
  console.log("uniqueNumbers: " + uniqueNumbers); 
  return uniqueNumbers;
}

console.clear();
removeDuplicates([1, 2, 3], [5, 2, 1, 4]);

However, the output in the console shows:

Console was cleared
result: 
current: 1
result.indexOf(current): -1
result: 1
current: 2
result.indexOf(current): -1
result: 1,2
current: 3
result.indexOf(current): -1
result: 1,2,3
current: 5
result.indexOf(current): -1
result: 1,2,3,5
current: 2
result.indexOf(current): 1
result: 2
current: 1
result.indexOf(current): -1
result: 2,1
current: 4
result.indexOf(current): -1
uniqueNumbers: 2,1,4

The concern arises as to why the slice statement is not functioning as intended and instead resets the result variable with the current value?

I initially expected that the line `result.splice(result.indexOf(current), 1)` upon finding a match would result in:

1,3,5

Instead of

2

Answer №1

Array#splice gives back the section of the array that was removed, and you're assigning it to the result variable.

You are recommended to utilize Array#slice instead:

function diff(args) {

  var diff = [].concat.apply([], arguments).reduce(
    function(result, current) {

      console.log("result: " + result);
      console.log("current: " + current);
      console.log("result.indexOf(current): " + result.indexOf(current));
      
      var index = result.indexOf(current);

      return index === -1 ?
        result.concat(current) :
        result.slice(0, index).concat(result.slice(index + 1));
    }, []
  );
  console.log("diff: " + diff);
  return diff;
}

console.clear();
diff([1, 2, 3], [5, 2, 1, 4]);

Answer №2

At this point, the current behavior of splice is as expected...

The return value includes an array with the deleted elements

If we substitute the ternary operator with an if, the logic becomes clearer. Here's the initial code snippet:

if (result.indexOf(current) === -1) {
    return result.concat(current)
} else {
    return result.splice(result.indexOf(current), 1);
}

In the original version, you were returning the removed element.

You should aim for this revised approach:

if (result.indexOf(current) === -1) {
    return result.concat(current)
} else {
    result.splice(result.indexOf(current), 1);
    return result;
}

Now, the element gets deleted first before returning the modified array.

Here's your updated snippet after incorporating these changes:

function diff(args) {
  var diff = [].concat.apply([], arguments).reduce(
    function(result, current) {

      console.log("result: " + result);
      console.log("current: " + current);
      console.log("result.indexOf(current): " + result.indexOf(current));

      if (result.indexOf(current) === -1) {
        return result.concat(current)
      } else {
        result.splice(result.indexOf(current), 1);
        return result
      }
    }, []
  );
  console.log("diff: " + diff);
  return diff;
}

console.clear();
diff([1, 2, 3], [5, 2, 1, 4]);

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

Passing null as a parameter in ngResource AngularJS

I am currently utilizing ngResource from AngularJS 1.2.1, and I'm encountering an issue when attempting to include null as a parameter value in a PUT request. It seems that Angular ignores the parameter entirely and does not send it along with the req ...

Breaking down the initial state within a redux reducer

Can you explain the distinction between returning state in the default case of a Redux reducer using return state and return { ...state } ? ...

What causes the failure of this select menu in the latest combination of jQuery and JQM?

I am looking to enhance this code, but I have noticed that it does not limit the selection (by count) in the newer versions of jQuery and JQM. Check out this example which demonstrates that it works with jQuery 1.8.3 and JQM 1.2.0. Here is the jQuery cod ...

Retrieve the content from paragraph elements excluding any text enclosed within span tags using the Document.querySelector method

Exploring the following element structure: <p> <span class="ts-aria-only"> Departure </span> RUH <span class="ts-aria-only">&nbsp;Riyadh</span> </p> In an attempt to extract the text RUH, it has been disc ...

React - Page Loads with Empty Query Parameters

Seeking assistance with navigation logic in React, I'm encountering an issue that requires some guidance. I have developed a front-end web app using TypeScript, React, and Ionic Framework V5. The app features a standard search box that redirects use ...

Displaying image behind bootstrap modal using Lightgallery js

Can anyone help me with an issue I'm having with previewing images using lightgallery js? The image is showing up behind the modal window. https://i.sstatic.net/FncZB.png I'm not sure why this is happening Here's the javascript code I am ...

Tips for showcasing a Bootstrap alert

I'm attempting to integrate Bootstrap Alerts into my project, but I'm struggling to display them programmatically. Here is the HTML snippet: <div class="alert alert-success alert-dismissible fade show" role="alert" id="accepted-meal-al ...

What could be causing my server to not fully read my json file?

I created a function that sends a get request for fav.json and assigned the id="fav_button" button to execute this function. Additionally, I configured an express server. However, upon clicking the button, only the last item in the json file is displayed. ...

What is the standard text displayed in a textarea using jQuery by default

My goal is to display default text in a textarea upon page load. When the user clicks on the textarea, I want the default text to disappear. If the user clicks into the textarea without typing anything and then clicks out of it, I'd like the default t ...

Applying reduce method for accessing object information within an array and transforming its structure

In my data structure, I have a list of deliveries that includes different cities and the number of units delivered to each city: var deliveries = [{ location: "Chicago", units: 10 }, { location: "San Francisco", units: 5 }, { location: ...

Exploring the Next and Previous Posts within the Same Categories on Blogger

First off, I recommend reading this article on implementing Next and Prev Buttons for Blogger Theme: Next and Prev Buttons for Blogger Theme Got the gist of what I'm aiming for? Let's move on to my query: I've already embedded code into th ...

What could be the reason for my array being nested inside another array as a value in a dictionary

I am having some difficulty understanding how the selected array is being returned in my dictionary. Could you please provide me with an explanation? The language being used is javascript. I have constructed a dictionary with arrays as values. However, wh ...

Executing tasks in a job on GitHub using Node.JS and .NET

I am currently in the process of developing a JavaScript API for a .NET project. In order to streamline my workflow, I would like to know if it is feasible to have GitHub actions set up with both Node.JS and various versions of .NET Core (2.1, 2.2, 3.0 or ...

Converting a JavaScript string containing an `import` statement into a browser-compatible function

Can my vue application transform the given string into a callable function? const test = 'import { pi } from "MathPie"; function test() { console.log(pi); } export default test;' The desired output format is: import { pi } from "M ...

Why is Firebug displaying an inaccessible JavaScript object property?

I am struggling to access the content of an object and can't seem to figure out why. It seems like maybe the properties that Firebug shows the object has are not actually there, or I might just be using the wrong syntax to access them. Here is the fu ...

Finding Text Between Two Distinct Strings Using Regular Expressions in JavaScript

I am currently utilizing AJAX technology. My approach involves sending a GET request that retrieves a raw HTML string representing the content of a webpage. I am grappling with the challenge of isolating all elements enclosed between div tags: <div ro ...

Can someone explain the meaning of [Object: null prototype] when using url.parse() with nodeJS?

I am currently diving into learning nodeJS for my project and still getting the hang of how nodeJS works. I have a question regarding a confusing issue I encountered while trying to use the .query method with url.parse(request.url, true). I keep seeing an ...

Tips for maintaining a scrollable Material-UI Table with dynamic height?

I'm encountering an issue with the Material-UI Table component in terms of its size and scrollability. Summary: The Material-UI table only becomes scrollable when its parent has a fixed size. If I set the size to 100% to fit the parent, it overflows. ...

AngularUI presents a unique feature of accordion header images

Currently in the process of transitioning my project from jQuery to AngularJS, here is the code snippet I have in jQuery: jQuery Code $(document).ready(function() { var icons = { header: "ui-icon-circle-arrow-e", activeHeader: "ui-icon-ci ...

Creating, customizing, and assigning values to data attributes in Draft-js blocks: A complete guide

My current setup involves a DraftJS editor displayed like this: <Editor editorState={this.state.editorState} handleKeyCommand={this.handleKeyCommand} onChange={this.onChange} placeholder="Write a tweet..." ref="editor" spellCheck={true} /&g ...