The implement of the filter function in JavaScript is a powerful tool

Recently, I encountered a challenge on Codewar. Below is my solution, but what piqued my curiosity is why both return e and return arr[i-1] yield the same outcomes.

var uniqueInOrder=function(iterable){
  
  let arry = typeof iterable === "string" ? iterable.split('') : iterable;
  
  return arry.filter(function(e,i,arr)
    { 
        if(i === 0)
        {
           console.log(e);
           return e;
        }
        else if(arr[i-1] !== e) 
          {
      
            console.log(arr[i-1] );
            return e;
            //return arr[i-1];
          }
      });
}
uniqueInOrder("aaaabbbccdaabbbab");

Answer №1

filter creates a brand new array by selecting the elements for which your callback function returns a truthy value. In this scenario, your code always results in a truthy value because when i is equal to 0, you return e which is one of the characters from the array, all of which are considered truthy. Similarly, if i is not equal to 0 and you were using the commented-out return arr[i-1], you would still be returning an element from the array.

Consequently, instead of filtering the array, you are essentially duplicating the array with your current implementation.

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

Exploring the intricacies of parsing nested JSON data

Could someone assist me with understanding the following json data? { "Message":"The request is invalid.", "ModelState":{ "model.ConfirmPassword":["The password and confirmation password do not match.","The password and confirmation passwo ...

Utilizing Ajax for Dynamically Filling a Dropdown Menu

My journey into the world of Ajax has led me to a state of confusion and frustration. The task at hand is to populate the first box with customer data from the database, then use the customerID to retrieve all vehicleID's using the select.php script. ...

Error encountered in React: When a parent component tries to pass data to a child

I have a Quiz object that I need to pass a single element of (questionAnswerPair) to a child component called QuestionAnswer. Although the Quiz data is fetched successfully and iterated through properly, there seems to be an issue with passing the Questio ...

Broadcasting real-time video from a webcam on an HTML website that is accessible locally through a Raspberry Pi device

My goal is to stream live video from a USB camera connected to my Raspberry Pi device onto a simple HTML site that is only visible on localhost. The site will be hosted on the Raspberry Pi itself and will only need to display the video streamed by the Ra ...

Issue with Intel XDK: the document.location.href is directing to an incorrect page

Hello Community of Developers, I have been experimenting with different methods but still haven't found a solution. In my project using Intel XDK, whenever I attempt to change the page using location.location.href = "#EndGame" or similar codes in Java ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

Struggling with calling rerenderEvents in FullCalendar using JQuery after a successful AJAX request

I seem to be encountering an issue where the calendar does not update after a POST request. Everything works smoothly until that point: $('#calendar').fullCalendar({ ... select: function (startDate, endDate) { $.ajax({ ...

Creating an object efficiently by defining a pattern

As a newcomer to Typescript (and Javascript), I've been experimenting with classes. My goal is to create an object that can be filled with similar entries while maintaining type safety in a concise manner. Here is the code snippet I came up with: le ...

Learn how to insert JavaScript code into the head of an iframe using jQuery

My goal is to inject javascript code into the head of an iframe using jquery with the code provided below. var snippets_js='<?php echo $snippets_javascript;?>'; var scriptjs = document.createElement("script"); scriptjs.type = "text/j ...

Issues arise when attempting to smoothly scroll to an anchor point in a webpage

While working on my website, I have encountered a challenge. The issue arises when dealing with multiple div items. Upon scrolling slightly, the entire page focuses on the div with a height of 100vh, which works perfectly fine. However, my attempts to ...

Angular Material Slider is failing to display properly

I am struggling to get the Angular Material Slider to render correctly in my project. Here is the code I have been using: <div class="row formField" ng-cloak> <div class="col-md-2"> <div>送貨日期</div> & ...

error 404 when sending a xhr request in node and react js

I am currently developing a basic login page in React that needs to connect to a database through an AJAX call to a Node.js file. Here is the Node.js code I have implemented: var express=require('express'); var app=express(); var db=require(&ap ...

add information to a JavaScript "JSON array"

When working in JS (specifically node/js but applicable to general JS), one common issue arises. Upon receiving JSON data from the server, there is often a need to modify it before presenting it on the view. How should this be approached? Creating additi ...

Using Javascript to upload an image and show it in a small display

Hey there, I have a functioning JavaScript code that loads an image uploaded by the user onto the HTML page. However, the issue is that the image doesn't have a set maximum height or width, causing buttons on the page to move out of view and become in ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

Is it not feasible to pass a local variable with the same name as a global variable in JavaScript?

const foo = "foobar"; function bar(){ const foo = foo || ""; return foo; } bar();` When running this code, it returns an empty string. Why is JavaScript unable to reassign a local variable with the same name as a global variable? Most other progra ...

Execute two queries using MongoDB and Node.js

I'm currently facing a minor issue that I can't seem to resolve. My challenge is to pass two queries to my add_people.ejs file. While I can successfully pass one query, I am unsure of how to pass the second one. Here is an example of what I have ...

Retrieve information from MongoDB using a custom date string in Javascript

As a newcomer to NodeJS, I have a MongoDB collection that stores the following Data: [{ _id: new ObjectId("6180c67a9b414de991a24c43"), cusDate: '20/11/2021 03:32 AM', cusName: 'Akila', cusEmail: ...

Adding a <tr> tag to an HTML table using JQuery and AJAX in the context of Django framework step by step

I am currently navigating the world of Javascript, Jquery, and Ajax requests and I'm encountering a challenge with how my scripts are executing. My homepage contains a lengthy list of items (over 1200) that need to be displayed. Previously, I loaded ...

Switch back and forth between adding and removing a table row using jQuery

Currently, I am developing a drop-down feature for a table that populates its data using MySQL. The functionality involves creating a new table row below the current one when a user clicks a button. However, instead of generating multiple new rows each tim ...