Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

Unable to monkey patch array using uniq in JS [beginner] in node js.

By M.K. Verma · 2 May 2022

Unable to monkey patch array using uniq in JS [beginner] in node js.
  1. You need to declare narr
  2. Your condition in your for loop makes no sense i < 0. You need the length of the array this.length
  3. Typo include its includes

 

Array.prototype.uniq = function() {
  let narr = [];
  for (let i = 0; i < this.length; i++) {
    if (!narr.includes(this[i])) {
      narr.push(this[i]);
    }
  }
  return narr;
}

console.log([1, 2, 2, 3, 3, 3].uniq());