Tips for managing a list of strings with a maximum length: Automatically remove the first string from the list when a new one

I am looking for a way to keep track of a list of strings with a maximum length.

For instance, I need to maintain a list with a maximum length of 3. I want to add new items to the list as long as its length is less than 3. However, once the length reaches 3 and I try to add a new item, I want to remove the oldest entry from the list.

const list = ["A", "B", "C"]
list.push("D")
// Your logic here

// The expected output should be ["B", "C", "D"]
console.log(list)

Does anyone have any suggestions on how to accomplish this?

Answer №1

shift removes the first element and then push adds a new element.

let myList = ['X', 'Y', 'Z'];
myList.length < 3 ? myList.push('W'): updateArray(myList);

function updateArray(myList){
 mylist.shift();
 mylist.push('W');
}
console.log(myList); 

Answer №2

To establish a rule for the maximum length, you can utilize a class:

class MaxLengthArray {

    private _array: string[];

    get array() {
        return this._array;
    }

    constructor() {
        this._array = [];
    }

    public insert(newValue: string) {
        if (this.array.length >= 3) {
            this.array.push(newValue);
            this.array.shift();
        } else {
            this.array.push(newValue);
        }
    }

}

Explore more on TypeScript here!

Answer №3

What we require is a Queue (slightly modified), a first in first out (FIFO) data structure.

class Queue<T> {
  _store: T[] = [];
  push(val: T) {
    if (this._store.length < 3) {
      this._store.push(val);
    } else {
      this._store.shift();
      this._store.push(val);
    }
  }

  GetQ() {
    return this._store;
  }

}

NOTE: The above class encapsulates the Queue. You may need to customize it according to your requirements.

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

Is there a way to include e.preventDefault() within an ajax call?

After the user clicks the submit button on my form, the handleSubmit function is triggered. However, I am having trouble calling e.preventDefault() inside my AJAX call due to its asynchronous nature. How can this issue be resolved? class FormRegister ex ...

Create a "Line" on the canvas by adjusting the attributes of the "Line" object using Three.JS

I have successfully created a cube and lines using Three.js. My goal is to position the lines around the cube as guidelines, as shown below: However, I am struggling to understand the properties of the line: var lengthVertArray = lengthLineGeometry.vert ...

Is it beneficial to utilize components in order to streamline lengthy HTML code, regardless of whether the components do not repeat and do not require any props (such as in Vue or any other JavaScript library

In the Vue.js team project I am currently involved in, I have structured my code in the view as follows: component01 component02 ... There are more than 10 components in total. Each component represents a section of the landing page, consisting mostl ...

Can the "spreadCall" function be effectively implemented? An enigma involving conditional typing and inference

One of the challenges I'm facing at work relates to a specific function. The function in question is the following: function spreadCall(f1, f2) { const args = f1(); f2(...args); } The issue is that we need f2 to accept an ex ...

What is the reason behind the absence of forEach method on NodeListOf?

Here is the code that I wrote: var checkboxes = this.element.querySelectorAll("input[type=checkbox]") as NodeListOf<HTMLInputElement>; checkboxes.forEach(ele => { var key = ele.name; if (data.hasOwnProperty(key)) { ...

Embed the Nest API into your HTML5 code

My mobile HTML5 application includes a script in the index.html file. Nest.js (code below) Whenever I run my application, I encounter an error stating that Firebase is not defined. This is odd because the function seems simple: --> var dataRef = new ...

A step-by-step guide on implementing the bootstrap paginator library to paginate PHP echoed data

I'm currently working on a project that involves displaying data from a database in a table. To make the data paginated on the client side, I decided to use the bootstrap paginator library available at: Below is the code I'm using: In my header ...

Ionic causing delay in updating ngModel value in Angular 2

My ion-searchbar is set up like this: <ion-searchbar [(ngModel)]="searchQuery" (keyup.enter)="search();"></ion-searchbar> In the typescript file, the searchQuery variable is defined as follows: export class SearchPage { searchQuery: string ...

Ensure that the div remains fixed at the bottom even when multiple items are added

Following up on the previous question posted here: Sorting divs alphabetically in its own parent (due to many lists) I have successfully sorted the lists alphabetically, but now I need to ensure that a specific div with a green background (class: last) al ...

Looking to add a bulleted list to an HTML document with PHP?

I have integrated a PHP script within an HTML list element that enables users to edit the HTML element directly from the webpage if they enter the correct password via the variable ?pw = "password". Now, I am looking to allow users to add new list items ...

Tips on how to utilize JavaScript to display data on a page without the need for refreshing, updating every 2-5

Could you please assist me? I am working on a CRUD application and have created a function called loaddata();. My issue is that when another user adds data, it should be displayed in my table without the need to refresh. Is there a way to achieve this? fun ...

The compiler does not recognize the TSConfig option 'lib' - please review and correct

I have inherited an angular 1 project written in typescript version 1.8.10. However, I am encountering compilation issues with the following error message: Unknown compiler option 'lib' If I remove the "lib" line, a cascade of other errors suc ...

Experiencing H12 and 503 errors while using the Heroku server

Every time I attempt to make a POST request on my Heroku app, I encounter a 503 error. Strangely enough, the functionality works perfectly fine when running the app locally. at=error code=H12 desc="Request timeout" method=POST path="/login" host=classes-t ...

Obtain specific fields from a multidimensional array object using lodash

My dilemma involves working with an object that has the following structure: var data = [ { "inputDate":"2017-11-25T00:00:00.000Z", "billingCycle":6, "total":1 },{ "inputDate":"2017-11-28T00:00:00.000Z", "bi ...

I'm trying to integrate a chatbot into my website using Node-RED. Can someone guide me on how to utilize the Bluemix Tone Analyzer to analyze the tone of the user

Creating a chat bot to ask psychological questions and analyze how a person is feeling has been my recent project. I managed to set up a chat bot in Bluemix, following a tutorial on integrating it into Node Red: https://github.com/watson-developer-cloud/no ...

What is the reason behind the occurrence of an error when attempting to iterate through an array of objects within my react.js component?

Here is an example of some code: class Stepper extends Component { state ={ quiz_data: [ patient_data: [ {name: "A", age: "1"}, {name: "B", age: & ...

web browser editing tool

Do you know which library was utilized to create this JSON editor? https://i.sstatic.net/kGpGz.png You can find it at . The editor efficiently checks the syntax and shows errors when necessary. ...

Creating dynamic form groups in Angular 4

I am currently working on a dynamic form group and I am facing a particular challenge. https://i.sstatic.net/m20IO.png Whenever I click on "add more," it should add 2 dynamic fields. Here is the function I am using: onAddSurgeries(){ const control = ...

What is the best way to transform a Ruby hash into a JavaScript object while maintaining unquoted values?

Is there a way to display a Ruby hash as a JS object without quotes for certain values in the hash, essentially as JS code? For instance, consider the following Ruby code: { foo: proc { 'someJavascriptFn()' } }.to_json How can I have the JS out ...

After an AJAX request is completed, the event.keyCode is not returning the key codes for the up and

I have a function that uses AJAX to autocomplete a text field. The results are added to a specific div element. I am trying to implement the functionality where users can navigate through the results using the up and down arrow keys. However, I am encoun ...