Javascript Array remove(elem)

Description

Javascript Array remove(elem)


Array.prototype.remove = function (elem) {
    var elemIndex = this.indexOf(elem);
    if (elemIndex > -1) {
        this.slice(elemIndex, 1);//w w w.  ja v a2s.co  m
        return true;
    }
    return false;
};

Javascript Array remove(elem)

class Time {//from ww w. j  av a2  s . c o  m
  static fromMinutesAndSeconds(minutes, seconds) {
    return new Time(minutes*60000 + seconds*1000);
  }

  constructor(milliseconds) {
    this.milliseconds = milliseconds;
  }

  getMinutes() {
    return (this.milliseconds/60000)|0;
  }

  getSeconds() {
    return ((this.milliseconds-this.getMinutes()*60000)/1000)|0;
  }

  isTimeLeft() {
    return this.milliseconds > 0;
  }

  decrement(amount) {
    this.milliseconds -= amount;
  }

  clone() {
    return new Time(this.milliseconds);
  }
}


Array.prototype.remove = function(elem) {
  let index = this.indexOf(elem);
  if (index < 0) {
    return;
  }
  this.splice(index, 1);
}

Javascript Array remove(elem)

"use strict";/* www  . ja  v  a  2  s .c o  m*/

/**
 * ### Problem 2. Remove elements
 * Write a function that removes all elements with a given value.
 * Attach it to the array type.
 * Read about **prototype** and how to attach methods.

 var arr = [1,2,1,4,1,3,4,1,111,3,2,1,'1'];
 arr.remove(1); //arr = [2,4,3,4,111,3,2,'1'];
 */

Array.prototype.remove = function(elem) {
    var i = 0;
    while(i < this.length){
        if(this[i] === elem){
            this.splice(i, 1);
        }
        i+=1;
    }
};

var arr = [1,2,1,4,1,3,4,1,111,3,2,1,'1'];
console.log("Initial array:");
console.log(arr);
arr.remove(1); //arr = [2,4,3,4,111,3,2,'1'];
console.log("After removing all 1:" );
console.log(arr);



PreviousNext

Related