The JavaScript code is producing a numerical output instead of the intended array

I am facing an issue with my program that is designed to eliminate items from a list of arguments.

function destroyer(arr) {
  var args = [].slice.call(arr);
  var data = args.shift();
  for(var i = 0; i < args.length; i++){
    var j = 0;
    while(j < data.length){
      if(args[i] == data[j]){
        data.splice(j,1);
        j = 0;
      }
      else{
        j += 1;
      }
    }
  }
  return data;
}

Even though the expected output of destroyer([1, 2, 3, 1, 2, 3], 2, 3) should be [1,1], I'm only getting '1' as a response. I have tested the function outside the loop and it's returning the correct array, so I'm confused about why it's not working within the loop.

After making some adjustments, here is the updated version:

function destroyer(arr) {
  var args = [].slice.call(arguments);
  var data = args[0];
  args.shift();
  for(var i = 0; i < args.length; i++){
    var j = 0;
    while(j < data.length){
      if(args[i] == data[j]){
        data.splice(j,1);
        j = 0;
      }
      else{
        j += 1;
      }
    }
  }
  // Remove all the values
  return data;
}

Answer №1

You have the option of utilizing spread syntax to gather the array of elements you want to remove and then using Array.prototype.filter to eliminate these elements from the original array, as demonstrated below:

function destroyer(arr, ...args) {
  return arr.filter(e => !args.includes(e));
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // [1, 1]

Answer №2

Utilizing the spread syntax is recommended in order to signify the presence of additional parameters

function destroyer(...arr) {
  var args = [].slice.call(arr);
  var data = args.shift();
  for(var i = 0; i < args.length; i++){
    var j = 0;
    while(j < data.length){
      if(args[i] == data[j]){
        data.splice(j,1);
        j = 0;
      }
      else{
        j += 1;
      }
    }
  }
  return data;
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

Answer №3

Another variation to consider.

function eliminate(array) {
  var position, arguments = [].slice.call(arguments, 1),
  arrayLength = array.length,
  newArr = [];
  
  while ((arrayLength -= 1) >= 0) {
    position = arguments.lastIndexOf(array[arrayLength]);
    if (!~position) {
      newArr.unshift(array[arrayLength]);
    }
  }

  return newArr;
};

console.log(eliminate([1,2,3,1,2,3], 2, 3));
console.log(eliminate([1,2,3,1,2,3], 1, 3));
console.log(eliminate([1,2,3,1,2,3], 1, 2));
console.log(eliminate([1,2,3,1,2,3], 1, 2, 3));
console.log(eliminate([1,2,3,1,2,3], 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

The value sent from the ajax call did not reach the PHP file as expected

Here's the code I'm working with: HTML and Javascript: function getValues(){ var filter; $.ajax({ type: "POST", url: "myphpfile.PHP?action=sek", data: "id=1", async: false, suc ...

Is there a way to automatically close one menu when another is opened by clicking?

When all other search results have failed to solve my issue, I resort to posting my own question. My problem involves opening hidden submenus in a website's main menu. However, when I open multiple submenus, they just stack above each other. Ideally, ...

Tips for transferring large data without a page redirect using jQuery's post method:

Seeking advice on how to send large data via jQuery POST without redirecting the page. I'm working on a mobile chat project where communication between user app and server is done using JSON. The issue arises when dealing with big data as the jsonGet ...

maintain visibility of website menu while scrolling

I am having trouble getting my drop-down menu to stay fixed at the top of the screen while scrolling down on my website. Despite several attempts, I have not been able to achieve this using the current CSS and menu setup. Can someone please assist me wit ...

Ways to block past dates on bootstrap date picker starting from the current date and how to prevent dates beyond 90 days in the future from being selected on the

I am currently facing an issue with disabling previous dates from the current date in my code. While the functionality works well for the "From Date" date picker, I am having trouble implementing the same restriction for the "To Date" date picker after 90 ...

Transform a React component from a regular function to an ES6 class

Recently delving into ES6 and React, I found myself navigating through various ways to write a React component. My journey began with "React.createClass," then transitioned to utilizing "extends React.Component" with ES6 classes syntax. While following a ...

Sending data between two elements when a jQuery event is triggered

As a JavaScript beginner, I am facing an issue where I need to push data from an h1 tag to a textarea. My website is built using WooCommerce and when a visitor clicks on a product, a chat box with the product title opens. Currently, I have successfully p ...

Latest news on KnockoutJS enhancements

Is there a way to create an HTML markup with a GIF progress bar that appears when the page is loading? I want to use Ajax to fetch data, populate the markup, and then hide the GIF. How can I achieve this functionality using KnockoutJS? var Item = functi ...

html interactive/expandable tree

I've come across this code which generates an HTML tree, but I'm facing an issue where the tree expands every time I refresh the page. What I want to achieve is to have certain branches expanded and others collapsed when the page is opened, depe ...

What could be the reason that the results of my quick sort function are not appearing on the screen

I'm having trouble getting any output from this code. Can someone help me figure out what's wrong? function Ascending() { var array = new Array(); array[0]=parseInt(document.getElementById("1").value); array[1]=parseInt(document.getElementById(" ...

Using jQuery to create a seamless transition in font size as you scroll

Currently, I have a jQuery animation function in place to adjust the font size of the .header-wrap text when the document is scrolled beyond 50px. While this method does work, I am not completely satisfied with it as the transition is not very smooth. Idea ...

"Transmit the document by utilizing the file ID in the form of

When sending a file from my server, I can easily define the path and it goes through successfully. However, with the node-telegram-bot-api, there is an option to send a document that is already hosted on telegram servers by providing the file_id in the doc ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

The styles applied to the Angular 5 Component host element are not being reflected correctly in jsPlumb

As a beginner in Angular >2 development, I am excited to build my first application from scratch. One of the features I'm trying to implement is drawing flow charts using jsPlumb. However, I have encountered an issue where the connectors are not be ...

Is it necessary to integrate the Facebook JavaScript SDK even if I do not plan on utilizing its features?

I have created some simple applications to use as custom tabs on my Facebook page, consisting of hyperlink images. I am not utilizing any of the functionality provided by the Facebook JavaScript SDK in these instances. Do I really need to load the Faceboo ...

Instructions on how to navigate to a class page by clicking a button in a ReactJS interface

I am currently working with React and have implemented 3 classes in separate files. The App.js file contains a navbar and button, which when clicked, displays a table from 'Table.js'. I have also added buttons in front of each row in the table th ...

Similar to the reference of $(this) in jQuery, there is a similar concept in Vue.js

When working with jQuery, the use of $(this) allows for accessing elements without relying on classes or ids. How can we achieve a similar outcome in Vue.js? ...

Utilizing JavaScript to retrieve input names from arrays

This is the HTML form that I am currently working with: <form action="#" method="post"> <table> <tr> <td><label>Product:<label> <input type="text" /></td> <td><label>Price:<label> ...

Using Typescript with Protractor for Dropdown Menus

As a newcomer to Protractor, I am looking to automate the selection of a dropdown. While I have some knowledge in JavaScript, I am currently working with typescript. Can someone advise me on how to select the dropdown option based on the text provided? Fo ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...