Delete duplicate jQuery array

I get a list of arrays through jQuery of each function.

  var spnTxt = '';
  var arr = $('#id').find('span').each(function(utval) {
       spnTxt = $(this).text();
  });

It gives me

["pet", "dog", "london", "class"]
["pet", "cat", "newyork", "weight"]
["tech", "phone", "spain", "hello2"]
["tech", "phone", "spain", "hello"]
["tech", "phone", "spain", "hello"]

In my example above, I should get

["pet", "dog", "london", "class"]
["pet", "cat", "newyork", "weight"]
["tech", "phone", "spain", "hello2"]
["tech", "phone", "spain", "hello"]

Which one is unique. And my code below does not work. I'm not sure if he is right.

var dup = {};
var arr = $('#id').find('span').each(function(utval) {
    spnTxt = $(this).text();
    if (dup[spnTxt])
        $(this).remove();
    else
        dup[spnTxt] = true;

});

Basically I want to remove a duplicate array if my rows in arrays are exactly similar to each other. How to achieve this

+4
source share
3 answers

to try

var newArr = [];

for (var i = 0; i < arr.length; i++) {
    if (!isArraySame(newArr, arr[i])) {
        newArr.push(arr[i]);
    }
}

console.log(newArr)

function isArraySame(ar, check) {

    var isIn = false;
    for (var j = 0; j < ar.length; j++) {
        var sliceArr = ar[j];
        if (ar[j].length == check.length) {
            var count = 0;
            for (var i = 0; i < check.length; i++) {
                if (check[i] == ar[j][i]) {
                    count++;
                }
            }
            if (count == check.length) {
                isIn = true;
                break;
            }
        }
    }
    return isIn;
}

Demo

or use this method to test the same array

function isArraySame(ar, check) {
    var strArr = check.join();
    var isIn = false;
    for (var j = 0; j < ar.length; j++) {
        if (ar[j].join() == strArr){
            isIn = true;
            break;
        }
    }
    return isIn;
}

arrayString DEMO

0
source

To compare arrays to make sure their general collection is the same, you can use jQuery is .

$(array4).is(array5)

true, . , , , , .

0

Here is a feature that will do the trick for you

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Credit refers to SO LINK

Create parent array var parentArray =array();

After the each()function returns you an array, just pushthis array into the parent array

parentArray.push(Your_array_from_the_each_loop);

So, after each cycle starts using the above function, compare it with the elements parentArray

You can loop through parentArray using $.each()jQuery function

$.each(parentArray,function(key,value){ //NOTE: $.each() is different that $('elem').each();
//do the comparison
});
0
source

All Articles