JZ.
JZ.

Reputation: 21877

Pop elements out of an array using JS

I have an array results = [duplicate, otherdup] that contains a list of duplicates

I have a regular original_array = [duplicate, duplicate, duplicate, otherdup, otherdup, unique, unique2, unique_etc]

How do I iterate through the results array (list) and Pop all but one from the original_array to look like this:

oringal_array = [duplicate, otherdup, unique, unique2, unique_etc]`

Upvotes: 0

Views: 1056

Answers (3)

David Hedlund
David Hedlund

Reputation: 129792

A simple unique function could look something like this:

Array.prototype.unique = function() {
   var uniqueArr = [];
   var dict = {};
   for(var i = 0; i < this.length; i++) {
      if(!(this[i] in dict)) {
         uniqueArr.push(this[i]);
         dict[this[i]] = 1;
      }
   }

   return uniqueArr;
};

You could then easily do:

var unique_array = original_array.unique();

Upvotes: 1

Code Maverick
Code Maverick

Reputation: 20415

I would use John Resig's Remove() method:

// Remove() - Completely removes item(s) from Array
// By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {

    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);

};

You can loop through your array and just pass the index you wanted removed to the Remove() function.

Upvotes: 1

zod
zod

Reputation: 12417

are you looking something like this

but before calling pop you will be checking it should be popp[ed out or not by running through a loop!!

http://www.tutorialspoint.com/javascript/array_pop.htm

Upvotes: 0

Related Questions