smarber
smarber

Reputation: 5074

Turning an array of jquery objects into a jquery set

I'd like to know how to convert an array of jquery objects to jquery object.

Actually, with find of jQuery I retrieve several elements, find returns a jQuery object on which I apply jQuery method such as clone, css ...

In my case, my elements being retrived, I need to remove duplicates. The I did it, my elements now are in an array and not in a jQuery object anymore.

How do I turn an array of jQuery objects into a jQuery object?

Below is my code:

  var $enfants = $('#parent').find('option.enfant');
  var keys = [];
  var values = [];

  $.each($enfants, function(i, e) {
      if (-1 !== $.inArray($(e).val(), keys) ) {
          keys.push($(e).val());
          values.push($(e));
      }
  });

  // This lasts 1ms
  // $enfants.clone().appendTo($('#inconnu'));

  // This lasts 14ms
  // $.each(values, function(i, e) {
  //     $(e).clone().appendTo($('#inconnu'));
  // });

Hope it's clear

UPDATE1

The code above works well but slower than without removing duplicates

Upvotes: 0

Views: 35

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Use filter() and keep them in jQuery object from the start and do everything in one loop

$enfants.filter(function(){
      if (-1 !== $.inArray(this.value, keys) ){
          keys.push(this.value);
          return true;
      }
}).clone().appendTo($('#inconnu'));

Upvotes: 1

Ted
Ted

Reputation: 14927

Try this, since the values array is already 'unique'. Note the change of pushing e instead of $(e) into values

var $enfants = $('#parent').find('option.enfant');
var keys = [];
var values = [];

$.each($enfants, function(i, e) {
      if (-1 !== $.inArray($(e).val(), keys) ) {
          keys.push($(e).val());
          values.push(e);
      }
  });

  $(values).clone().appendTo($('#inconnu'));

Upvotes: 0

Related Questions