Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
How can we update or refresh/renew filtered array?-javascript

updating filtered array every time original array adds/inputs a new element


so every time I input a new element in the original array, then the filtered array gets refreshed and considers if the new element is in its condition

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

What about this, i am overriding the push method of the original array, so that when an new element is added, another method is going to get called to refresh the filtered array:

var originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var filteredArray = [...originalArray];
var filters = [];

// FUNCION THAT RECEIVES AN ARRAY AND OVERRIDES THE PUSH METHOD 
//SO THAT IT CAN EXECUTE A FUNCION AFTER PUSHING THE NEW ELEMENT
var AddEventToArrayPush = (arr, callback) => {
    arr.push = function(e) {
        Array.prototype.push.call(arr, e);
        callback(arr);
    };
};

var ResetFilters = () => {
    filters = [];
    filteredArray = [...originalArray];
}

var AddFilter = (filter) => {
    filters.push(filter);
}

var ApplyFilters = () => {
    filteredArray = [...originalArray];

    for (const filter of filters) {
        filteredArray = filteredArray.filter(filter);
    }
}

//CALLING THE FUNCTION TO OVERRIDE PUSH METHOD FOR THE ORIGINAL ARRAY
AddEventToArrayPush(originalArray, ApplyFilters)

// SOME FILTERS
const IS_EVEN_NUMBER = (number) => { return number % 2 == 0 };
const IS_GREATER_THEN_5 = (number) => { return number > 5 };

console.log("Initial filtered array:");
console.log(filteredArray.toString());

console.log("\r\nFiltering even numbers greater than 5");
AddFilter(IS_EVEN_NUMBER);
AddFilter(IS_GREATER_THEN_5);
ApplyFilters();

console.log("\r\nFiltered array after applying filters:");
console.log(filteredArray.toString());

originalArray.push(20);

console.log("\r\nFiltered array after pushing new element into original array:");
console.log(filteredArray.toString());
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!