I'm curious as to why the for-of loop within the function isn't producing the anticipated results that the regular for loop is achieving

Why is the behavior of the for...of loop different from the traditional for loop within this function? It appears that the 'el' in the for...of loop does not behave the same as iterable[i] in the regular for loop?

var uniqueInOrder = function(iterable){
     let unique = [];
     for(let el of iterable){
         let cur = el;
         let next = el + 1;
         if(cur !== next){
             unique.push(cur)
         }
     }
     return unique;
}
uniqueInOrder('AAAABBBCCDAABBB')  // unexpected output

// Returns expected output
var uniqueInOrder = function(iterable){
     let unique = [];
     for(var i = 0; i < iterable.length; i++){
         let cur = iterable[i];
         let next = iterable[i + 1];
         if(cur !== next){
             unique.push(cur)
         }
     }
     return unique;
}
uniqueInOrder('AAAABBBCCDAABBB') // ----> ["A", "B", "C", "D", "A", "B"]

Answer №1

The error lies within your initial function.

It's important to note that in JavaScript, the use of element in for (let element of iterable) {} is distinct from using i in a traditional for loop. Therefore, when you write let next = el +, you are essentially adding 1 to an element, not a number (resulting in something like 'A' + 1, as @Seblor pointed out).

To summarize, remember that el and i are not interchangeable.

Answer №2

As mentioned by @Sxribe, the for/of loop behaves differently and using el+1 to fetch the next value won't work.

An alternative approach to achieve the same outcome with both loops is as follows:

const uniqueInOrder = function(iterable){
     let unique = [];
     let prev = ''
     for(let el of iterable){
         let cur = el;
         if(cur !== prev){
            prev = el
             unique.push(prev)
         }
     }
     return unique;
}
console.log(uniqueInOrder('AAAABBBCCDAABBB'))

// Outputs the expected result
const uniqueInOrder = function(iterable){
     let unique = [];
     for(var i = 0; i < iterable.length; i++){
         let cur = iterable[i];
         let next = iterable[i + 1];
         if(cur !== next){
             unique.push(cur)
         }
     }
     return unique;
}
console.log(uniqueInOrder('AAAABBBCCDAABBB'))

In this scenario, we compare the current value against the previous one instead of the next one.

Answer №3

According to @Sxribe's explanation, you should focus on obtaining the element rather than the count of i.

To achieve this, you must verify if the el exists in the array and then add it to the array if it doesn't already exist. An implementation similar to the following could accomplish this:

function findUniqueElements(iterable) {
    let uniqueElements = [];
    for (let el of iterable) {
        let currentElement = el;
        if (uniqueElements.indexOf(el) === -1) {
            uniqueElements.push(currentElement);
        }
    }
    return uniqueElements;
}

console.log(findUniqueElements('AAAABBBCCDAABBB'));

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

Sending a JSONP request to a PHP script

For my application submission, I am trying to send a JSON object to a PHP script that will return a JSON response. The challenge here is that the domain does not comply with the same-origin policy, meaning the JSON is being sent from a different domain. Up ...

`When utilizing $routeParams, the CSS fails to load`

Whenever I use parameters in ngRoute and go directly to the URL (without clicking a link on the site), the CSS fails to load. All my routes are functioning properly except for /chef/:id. I utilized yeoman's angular generator, and I am running everythi ...

express routes are failing to execute the function

When I navigate to routes in my browser, the results are displayed in my console but the server call seems to be running for a long time in the network. Can anyone provide some assistance? My controller, var express = require('express'); var ...

Simulate a left mouse click on the swf object once the page has fully loaded

My website now features a flash game that inexplicably requires a left mouse click on the page after loading in order to enable arrow key functionality. I attempted using a JavaScript-based mouse trigger in my HTML code and assigned an ID to the flash obj ...

Nested loops in JavaScript can be combined with promises to efficiently handle

I am facing a challenge in looping through an array that contains another array as one of the parameters. My goal is to iterate through this nested array according to specific requirements, and then execute a function once the parent loop is finished. Can ...

What is the best way to extract individual words from a string based on a specified list of tokens?

I am currently working with a list of tokens used to create artificial Japanese words, which is represented by the following array: var syllables = ["chi","tsu","shi","ka","ki","ku","ke","ko","ta","te","to","sa","su","se","so","na","ni","nu","ne","no","ha ...

Animating numerous elements simultaneously during Vue component rendering

Take a look at this simple case in the following jsfiddle: https://jsfiddle.net/hsak2rdu/ I attempted to swap and animate two elements, but it didn't work as expected. When you click the toggle button in the playground, the second element quickly mo ...

Retrieve the values of the recently selected options in a multiple selection

I am trying to retrieve the last or most recently selected option value from a dropdown menu. In my Django code, I have attempted the following: <script type="text/javascript> django.jQuery(document).ready(function(){ django ...

Float over a specific line in a drawing

I am looking to develop a unique rating system using css, html, and potentially js : https://i.sstatic.net/pQP79.png My goal is for the user to hover over a specific section of a circular stroke and have it fill with a particular color, all while maintai ...

Italian calendar conversion for the react-multi-date-picker library

I recently integrated the react-multi-date-picker into my project, utilizing the multiple mode feature. However, I encountered an issue when trying to display the Italian calendar based on the language setting. Despite using locale="it", the calendar was n ...

The error message "Create controller with service — Get... is not a function" indicates that

Within my ASP.NET Boilerplate project, the following code snippet is present: (function () { appModule.controller('augustinum.views.kostenstelle.index', [ '$scope', '$uibModal', 'abp.services.app.kostenstelle ...

Is it possible to insert a second hyperlink into a JavaScript-occupied anchor?

Check out my reference page at: To change the content in a 'containerarea' div, I am utilizing Dynamic Drive's "Dynamic Ajax" script. Below is an example of the anchor code used: <a href="javascript:ajaxpage('videos-maintenance/app ...

Obtaining the route name in Vue.js within the App.vue component

After utilizing vue-cli with webpack to construct the vue project, I incorporated vue-meta-info for SEO purposes. I am facing an issue in setting up the page title using templates and route names. Unfortunately, I am unable to access the variable in the r ...

Maintain the current states when returning to a previous point in time

In my Angular app, I have multiple pages that allow users to make changes such as opening tabs and pills, modals, etc. For instance, if a user opens a modal and then clicks a link within that modal that takes them to another page, I want the original page ...

What is the best way to update a canvas chart when the side menu is hidden?

I am facing an issue with the layout of my webpage, which includes a left side menu and a canvas chart. The left side menu occupies the first 155 pixels of the width, leaving the rest for the canvas chart set to a width of 100%. However, when I close the ...

I am seeking to redirect to a different page within an ejs template by clicking on a link

I am having trouble navigating to the next page using a link and keep getting a 404 error. I recently switched my template from jade to ejs. <html> <body> <div> <ul style="color:white; float: right;" class="nav navbar-nav ...

Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this: npm run custom-function "Hello, World". Currently, I have a file called src/myFunction.ts: import * as e ...

Verify if there is a cookie available; then execute the load() function. If the cookie matches, it is necessary to

$(document).ready(function() { var hrefs = { "en": ["includes/test1.html", "includes/test2.html"], "es": ["includes/test3.html", "includes/test4.html"] } $(function() { var cookie = Cookies.get('langCookie'); if (cookie) { ...

Is there a way to automatically remove a document in MongoDB and Node.js once its expiration date has passed?

I'm working on an appointment booking app and I need to automatically delete booking details after the booked date has passed. How can I make this happen? I attempted to use node-scheduler for this task, but it wasn't successful. The app itself ...

Encountered an unhandled runtime error: TypeError - the function destroy is not recognized

While working with Next.js and attempting to create a component, I encountered an Unhandled Runtime Error stating "TypeError: destroy is not a function" when using useEffect. "use client" import { useEffect, useState} from "react"; exp ...