Javascript Array except(keys)

Description

Javascript Array except(keys)


Array.prototype.except = function(keys){
    return this.filter((x,i) => keys instanceof Array
        ? !keys.includes(i) //  w  w w  . j a v a  2s .com
        : i !== keys)
};

Javascript Array except(keys)

Array.prototype.except = function(keys)
{
  let arr = this.map((i) => i);
  if(keys.length) {
    keys.sort((a,b) => a - b);/*w w  w. j  ava  2 s.  com*/
    keys.forEach((k, i) => { arr.splice(k - i, 1);});
  } else {
    arr.splice(keys, 1);
  } 
  return arr;
}

Javascript Array except(keys)

Array.prototype.except = function (keys) {

    var removed = [];

    if(Array.isArray(keys))
    {/*from  ww  w  .j a  va 2  s .c  o m*/
        for(var i = 0;i<this.length;i++)
        {
            if(keys.indexOf(i) == -1)
            {
                removed.push(this[i]);
            }
        }
    }
    else
    {
        for(var i = 0;i<this.length;i++)
        {
            if(i != keys)
            {
                removed.push(this[i]);
            }
        }
    }

    return removed;

};


var array = [1, 2, 3];
var res = array.except([1]);

console.log(res);

Javascript Array except(keys)

/**//from ww w .  jav a  2s.c o  m
 * Created by Sestri4kina on 21.01.2017.
 *
 * Extend the array object with a function to return all elements of that array,
 * except the ones with the indexes passed in the parameter.
 */
Array.prototype.except = function(keys){
    return this.filter((x, index, arr) => {
        return (typeof keys === 'number') ? (index !== keys) :
        keys.indexOf(index) === -1;
    });
};

var arr = ['a', 'b', 'c', 'd', 'e'];

var result = arr.except([1,3]);
console.log(`Should return: ['a', 'c', 'e']. Output is: ${result}
`);

var result1 = arr.except(1);
console.log(`Should return: ['a', 'c', 'd', 'e']. Output is: ${result1}
`);



PreviousNext

Related