开发者

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, u开发者_开发百科nique, 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]`


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();


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜