Eliminate consecutive identical values in an array

Imagine having an array of numbers like this:

const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];

The objective is to eliminate duplicate values only if they are next to each other. Therefore, the expected output for the given sample would be:

[2, 0, 2, 3, 0, 1]

Although I've made progress in solving this using a recursive method, there seems to be an issue preventing the generated result from being returned (although you can see it in the log before the return condition).

const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];

const remAdjDups = (arr, output = []) =>
{
    if (!arr.length)
    {
        console.log("Result before return: ", output);
        return output;
    }

    if (arr[0] === arr[1])
    {
        arr.splice(1, 1);
        remAdjDups(arr, output);
    }
    else
    {
        remAdjDups(arr.slice(1), output.concat(arr[0]));
    }
}

let out = remAdjDups(input.slice());
console.log("output: ", out);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Therefore, first and foremost, I would like to gain insights into what is happening with my approach, and secondly, I am open to any alternative solution (of any kind) that could tackle this problem.


Revised Solution

In case anyone is curious, I have successfully resolved this problem using recursion as follows. While I acknowledge that the filter solution is shorter and more elegant, I chose to practice solving it recursively.

const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1, 1, 1, 1];

const remAdjDups = ([x, y, ...rest], out = []) =>
{
    if (!rest.length)
        return (x === y) ? [...out, x] : [...out, x, y];
    else if (x === y)
        return remAdjDups([x, ...rest], out);
    else
        return remAdjDups([y, ...rest], [...out, x]);
}

let out = remAdjDups(input.slice());
console.log("output: ", out);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Answer №1

Just a quick tip for your solution: don't forget to include return before remAdjDups(arr...

By the way,

I utilized Array.prototype.filter in my implementation

const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];

const result = input.filter((i,idx) => input[idx-1] !== i)

console.log(result)

Answer №2

One effective method is using the filter function.

const data = [7, 8, 9, 2, 6, 4, 3, 2, 1, 1];

const output = data.filter((num, index) => {
 if(index !== 0){
  return data[index-1] !== num;
 }
 return num;
})

console.log(output)

Answer №3

The concept of recursion through mathematical induction is quite effective in solving this particular issue:

  1. If the initial element, a, happens to be null, then the outcome will be an empty set
  2. (induction) Assuming that the first element is not null, if the second element, b, is found to be null, return a single array consisting of just the first element, a
  3. (induction) In cases where neither the first element nor the second element are null, and when a equals b, the recursive outcome will have a removed
  4. (induction) For situations where both the first and second elements exist and are unequal, the end result should maintain the presence of both a and b in the recursion

const removeDuplicates = ([ a, b, ...additional ]) =>
  a == null
    ? []                                 
: b == null
    ? [ a ]                              
: a === b
    ? removeDuplicates([ b, ...additional ])         
: [ a, ...removeDuplicates([ b, ...additional ]) ]  

const dataset =
  [2, 2, 0, 2, 3, 3, 3, 0, 0, 1, 1];

const finalOutcome =
  removeDuplicates(dataset)
  
console.log(finalOutcome)
// [ 2, 0, 2, 3, 0, 1 ]

Answer №4

Your method is on the right track, but you simply overlooked returning the result from the recursive function call. Just ensure to include a return statement.

const numbers = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];

const removeAdjacentDuplicates = (array, output = []) =>
{
    if (!array.length)
    {
        console.log("Result before returning: ", output);
        return output;
    }

    if (array[0] === array[1])
    {
        array.splice(1, 1);
        return removeAdjacentDuplicates(array, output);
    }
    else
    {
        return removeAdjacentDuplicates(array.slice(1), output.concat(array[0]));
    }
}

let finalOutput = removeAdjacentDuplicates(numbers.slice());
console.log("Final Output: ", finalOutput);

I trust this clarifies it for you!

Answer №5

Remember to incorporate the return statement within both the if and else blocks of your code to prevent undefined from being returned.

if (arr[0] === arr[1])
{
    arr.splice(1, 1);
    return remAdjDups(arr, output);
}
else
{
    return remAdjDups(arr.slice(1), output.concat(arr[0]));
}

Alternatively, you can use a different approach utilizing Array#reduce

const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1, 1, 1, 6, 3, 3, 5, 8, 8, 0, -1, -1, 2, 56, 57, 56];

const arr = input.reduce((acc, ele, idx) => {
  if(ele !== input[idx + 1]){
   acc.push(ele)
  }
  return acc;
}, []);

console.log(arr);

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

Discovering the name, id, and class attributes of a RadioButtonList within a content placeholder using JavaScript

Working on a web forms project with a Master Page implementation, I have added the following code in my content place holder. <asp:RadioButtonList ID="ckbLstPartner" runat="server" name="ckbLstPartner" RepeatDirecti ...

JavaScript still displaying empty values despite correct syntax being used

Here is the HTML form I have created: <form accept-charset="utf-8" onsubmit="return validateForm()"> <input placeholder="Enter Username" type="text" id="user"> <input placeholder="Enter Your Password" type="password" id="pass"> ...

It is not possible to use an index of type 'item' to subscript a value of type '[item]'

I've been attempting to iterate through an array within a JSON structure, but no matter what I try, I keep encountering the error "Cannot subscript a value of type '[item]' with an index of type 'item'. I am able to print the value ...

Is it possible to use Selenium WebDriver to automate an HTML5 webpage?

Within my application, there lies an HTML5 webpage. While attempting to inspect it and retrieve IDs/classname locators, I have encountered difficulties in obtaining the necessary locators for specific web elements. I have noticed that many of these elemen ...

What is the best way to analyze and contrast two large 2D NumPy arrays with dimensions of 40,000 by 40,000?

Looking to compare two NumPy arrays of floats, both around the order of 10^-3 or smaller and with a size of 40k × 40k. The key requirement is for them to be identical. Is there a way to directly display or identify the differing elements? I experimented ...

Unable to supersede CSS module styling using global or external stylesheets in React, Next.js, or React Native

I'm facing a challenge finding a solution to a basic issue. I have a component that is initially styled using a class from a *.module.css file. However, I want to replace this style with one from a global stylesheet or another stylesheet but I can&apo ...

Checking phone numbers in JavaScript utilizing regular expressions while retaining the same keypress functionality

Using regular expression in JavaScript, validate a phone number with functionality similar to keypress. $('#phone').keypress(function(e) { var numbers = []; var keyPressed = e.which; for (var i = ...

How to handle event methods with Vue

Currently, I am facing a challenge in passing an event downward with a bound change listener to a child input component. Although I am utilizing wrapped input components, my goal is to define methods within the parent component. //App.js: <currency-inp ...

Ways to determine if a website element is hidden from view

I am currently investigating the visibility of the following element: <ul class = 'pagination-buttons no-bullets'> https://i.sstatic.net/oOo7S.png When <ul class = 'pagination-buttons no-bullets'> is visible, its parent el ...

Switch up the color of checkboxes with a dropdown menu option

I have an HTML dropdown code and I am trying to trigger a click event when a specific value is selected. Once this value is clicked, I want some checkboxes to change color. <select> <option value="calculate">calculate</option> ...

When dynamically binding onclick events within a for loop, all buttons end up with the same value

I'm currently working on a project where I am creating buttons dynamically and assigning an alert function for each one upon a click event. Here is the JavaScript function: function GenerateButtons(tabObj) { for (var t = 0; t < tabObj.views.vie ...

What is the best way to delete a specific section from a PHP file using PHP?

I have a project where I need to upload files to a server, but I want to store them in a PHP file... That's fine. However, when I attempt to delete them from the array using str_replace() it doesn't work... Here is the array: $files = array( &a ...

What is the proper method for incorporating permitted symbols into an HTML input form?

I am currently working on creating my own input tag with a field specifically for phone numbers: <base-input style="margin-bottom: 15px; width: 100%; max-width: 510px;" v-model="phone" type="tel" ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

Error in setting jQuery cookie causing malfunction

Jquery: // handle loading content $(".link").click(function(e) { e.preventDefault(); $(".nav_head li a").removeClass('active-link'); $(this).addClass('active-link'); var title = $(this).text(); $(".head .blue").text ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' https://i.sstatic.net/a16DD.png I tried running different ng bui ...

Guide to implementing the collapsible start and stop button feature in Angular

Having an issue in my Angular application with the dashboard page. I've created a button for start or stop (toggle functionality) but it's not working as expected. .component.ts toggleCollapse(jammer) { this.jammer.isCollapsed ? 'START& ...

Experimenting with the speechSynthesis API within an iOS webview application

I'm currently working on developing an app that features TTS capabilities. Within my webview app (utilizing a React frontend compiled with Cordova, but considering transitioning to React Native), I am implementing the speechSynthesis API. It function ...

Using Jquery to create interactive and dynamic webpage elements

I am struggling with a paragraph containing words in a span that are editable upon clicking. The content needs to be dynamically called, but my current approach is not effective. Can anyone provide a solution or a better way to achieve this? Feel free to ...

An alternative solution for supporting Edge Chromium is utilizing synchronous AJAX requests within the beforeunload event

While attempting a synchronous ajax request during the beforeunload event, I encountered an error stating that synchronous ajax requests are not supported in chromium browsers during page unload events. I am seeking alternatives for making a synchronous a ...