The functionality of the JavaScript array filter appears to be functioning properly; however, it does not display any output on

  1. As the array (2001, 1999, 2000 and 2002) grows by 4 years
  2. The array is displayed on the screen, featuring the same 4 years
  3. It's determined that the highest year is 2002
  4. 2002 is then removed from the array
  5. The array is again shown on the screen with all 4 years still present
  6. Surprisingly, it turns out that after deleting 2002, the maximum year is now calculated as 2001

What seems to be the issue?

const output = document.getElementById('output');

function handleYears() {
    let years = [];
    let addYear = function(newYear) {
        years.push(newYear);
    }
    let deleteYear = function(yearToDelete) {
        years = years.filter(item => item !== yearToDelete)
    }
    let calculateMaxYear = function() {
        return Math.max(...years);
    }

    return {
        years: years,
        addYear: addYear,
        deleteYear: deleteYear,
        calculateMaxYear: calculateMaxYear
    }
}

let newHandleYears = handleYears();

newHandleYears.addYear(2001);
newHandleYears.addYear(1999);
newHandleYears.addYear(2000);
newHandleYears.addYear(2002);

output.innerHTML += `<p>Years: ${newHandleYears.years}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
output.innerHTML += `<p>The item "${newHandleYears.years[newHandleYears.years.length - 1]}" will now be deleted from the "years" array.</p>`;

newHandleYears.deleteYear(2002);

output.innerHTML += `<p>Years: ${newHandleYears.years}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
body {padding: 0.5rem 1rem;}
<div id="output"></div>

Answer №1

Make sure to include the this keyword when reassigning a value in order to maintain the same reference when using push.

const output = document.getElementById('output');

function handleYears() {
    let years = [];
    let addYear = function(newYear) {
        years.push(newYear);
    }
    let deleteYear = function(yearToDelete) {
        this.years = years.filter(item => item !== yearToDelete)
    }
    let calculateMaxYear = function() {
        return Math.max(...this.years);
    }

    return {
        years: years,
        addYear: addYear,
        deleteYear: deleteYear,
        calculateMaxYear: calculateMaxYear
    }
}

let newHandleYears = handleYears();

newHandleYears.addYear(2001);
newHandleYears.addYear(1999);
newHandleYears.addYear(2000);
newHandleYears.addYear(2002);

output.innerHTML += `<p>Years: ${newHandleYears.years}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
output.innerHTML += `<p>Delete item "${newHandleYears.years[newHandleYears.years.length - 1]}" from "years" array.</p>`;

newHandleYears.deleteYear(2002);

output.innerHTML += `<p>Years: ${newHandleYears.years}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
body {padding: 0.5rem 1rem;}
<div id="output"></div>

Answer №2

Once a year is deleted, the newHandleYears object does not update with the new years value but retains the old one. To get the updated value, you can create another getter method for years:

const output = document.getElementById('output');

function handleYears() {
    let years = [];
    let addYear = (newYear) => {
        years.push(newYear);
    }
    let deleteYear = (yearToDelete) => {
        years = years.filter(item => item !== yearToDelete)
    }
    let calculateMaxYear = () => {
        return Math.max(...years);
    }
    let getYears = () => {
        return years
    }

    return {
        getYears: getYears,
        addYear: addYear,
        deleteYear: deleteYear,
        calculateMaxYear: calculateMaxYear
    }
}

let newHandleYears = handleYears();

newHandleYears.addYear(2001);
newHandleYears.addYear(1999);
newHandleYears.addYear(2000);
newHandleYears.addYear(2002);

output.innerHTML += `<p>Years: ${newHandleYears.getYears()}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
output.innerHTML += `<p>Delete item "${newHandleYears.getYears()[newHandleYears.getYears().length - 1]}" from "years" array.</p>`;

newHandleYears.deleteYear(2002);

output.innerHTML += `<p>Years: ${newHandleYears.getYears()}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
body {padding: 0.5rem 1rem;}
<div id="output"></div>

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

initial render results in undefined data

function Story() { let { id } = useParams(); const pin = useSelector(state => state.pins.pin); const dispatch = useDispatch(); const userid = 2 useEffect(() => { dispatch(getPin(id)); }, [dispatch, id]); return ( <div classN ...

How to stop Accordion from automatically collapsing when clicking on AccordionDetails in Material-UI

I am working on a React web project with two identical menus. To achieve this, I created a component for the menu and rendered it twice in the App component. For the menu design, I opted to use the Material UI Accordion. However, I encountered an issue wh ...

How can Cheerio help you effortlessly and stylishly locate tags that meet various specific criteria?

I am attempting to scrape data from the webpage . Specifically, I am looking for all the <li> tags that are nested within an <ul> tag, which in turn is located inside a div with the class mw-parser-output and has a property of title. Is there ...

Discover the syntax for reading route parameters in Angular

Currently, I am integrating the Paypal API into my project. After confirming a purchase, Paypal redirects to a specified URL. I set the desired URL as "localhost:4200/shop/order". However, when Paypal returns the URL, it appends the token and payerid at th ...

Disable the form options listed on the table

I have a scenario where I have a table and a form containing a dropdown list: <table> <tr> <td class="text">Apple</td> <td class="name">John</td> </tr> <tr> <td class=" ...

Merging 3 arrays with the Zip function to create a triple Tuple

I currently have an Array structured as follows: val a1 = Array("a","b","c") var a2= Array("Apple","Box","Cat") var a3= Array("Angel","Ball","Count") While I can use the zip function to create a tuple of two arrays, I'm interested in achieving a res ...

Utilizing JSON API filtering within a Next.js application

Recently delving into the world of coding, I've embarked on a personal project that has presented me with a bit of a challenge regarding API filtering. My goal is to render data only if it contains a specific word, like "known_for_department==Directin ...

PHP AJAX Serial Port Text Input Command

Recently, I've been delving into the world of PHP and AJAX. Despite being a newcomer, I've managed to grasp some basic concepts over the past few weeks. Along the way, I've relied on various posts from this platform for guidance, so when a p ...

Guide on extracting the text from the <script> tag using python

I'm attempting to extract the script element content from a generic website using Selenium. <script>...</script> . url = 'https://unminify.com/' browser.get(url) elements = browser.find_elements_by_xpath('/html/body/script[ ...

Extract data from the internal JSON resource file

I am a beginner attempting to decode this JSON data from a resource file, but I have been unsuccessful so far. While I can read the JSON content, I'm facing challenges in parsing it. Here is the JSON data I am working with: {"kind": "response", "co ...

Determining the height of the first element in jQuery

I am dealing with multiple elements that share the same class but have different heights. The class 'xyz' is only for styling borders, as shown below: <div class='xyz'></div> //1st element height=10px <div class='xy ...

Having trouble troubleshooting this issue where the object data is displaying in the console, but encountering an error when trying to use the resetValue

Index.html I am facing an issue while reading data from an object and the seek bar is giving a null error. The images and songs are stored locally, and I am trying to access them. <div class="music-player"> <div class="song&qu ...

There was a failure to establish a Redis connection to the server with the address 127.0.0.1 on port 6379

Currently, I am working with node.js using expressjs. My goal is to store an account in the session. To test this out, I decided to experiment with sessions by following the code provided on expressjs var RedisStore = require('connect-redis')(ex ...

Traveling within a layered object

Currently, I'm working with an object and iterating through it to retrieve outputs as shown below: var obj = { "first": { "Bob": { "1": "foo", "2": "bar" }, "Jim": { "1": "baz" } }, "second": { "Bob": { ...

Implementing Fullpage.js with persistent elements throughout slides

Can I keep certain elements fixed between slides? I found that the only way to accomplish this was by placing the text element outside of the slide div. <div class="section" id="section1"> <div class="intro"> <h1> ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

The front-end is responsible for removing the last item from an array

Having an issue with my React code. Here is my parent component: class RoomPrice extends React.Component { constructor(props){ super(props) this.state = { room: this.props.room, prices: [] }; this.handleDeletePrice = this.h ...

Sorting in MongoDB aggregation operations

I have a database containing user activities, and I want to calculate the number of active users and activities they performed each month. The results should be sorted by year first and then by month within each year. Here is my query: query = { ...

What's preventing the `@change` trigger from functioning properly with v-data-picker?

In my Vue.js application, I am utilizing the v-calendar package. I am trying to pass selected date range values to the parent component. However, why is the @change trigger not working? Parent.vue: <template> <div> <Child @set ...