0

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]`

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Will this work with JQuery? I notice prototype in this function
@JZ: yes, this is plain native javascript. It is true that Prototype is the name of another javascript library, but it's named so because it makes heavy use of prototyping, which is native to javascript.
1

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.

8 Comments

Will this work with JQuery? I notice prototype in this function
Yes. jQuery is simply a JavaScript library.
My use case is a scenario where I needed to keep track of my open jQuery UI dialogs. I stored the dialog id's in an array called openDialogs. When a dialog is closed, I would get the index of the dialog in my array by using var index = $.inArray("some-dialog-id", openDialogs);, and then pass that to the remove() function like: openDialogs.remove(index);
Isn't Prototype a competing library?
Not sure, but I know that jQuery uses prototype. Just open the jQuery file and do a search for prototype = and you will see.
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.