0

I am adding objects to an array like so:

fontSizeArray.push({element: $(y).prop("tagName").toLowerCase(), orginalSize:$(y).css("font-size"), size:$(y).css("font-size")});

this code inside a loop, what I am trying to do is eliminate the duplicates because some items will have the same tagName and the same font-size

I am trying to use in array, but its not working, the duplicates still remain.

if($.inArray({element: $(y).prop("tagName").toLowerCase(), orginalSize:$(y).css("font-size"), size:$(y).css("font-size")}, fontSizeArray) == -1)
                {
                        fontSizeArray.push({element: $(y).prop("tagName").toLowerCase(), orginalSize:$(y).css("font-size"), size:$(y).css("font-size")});
                }

What am I doing wrong?

4
  • Check this article stackoverflow.com/questions/18867599/… Commented Mar 13, 2017 at 0:25
  • I dont know how this article helps. Commented Mar 13, 2017 at 0:34
  • Sorry should have been this article stackoverflow.com/questions/19111707/… Commented Mar 13, 2017 at 1:22
  • @user979331 did you find useful my answer? if yes please don't forget to mark as correct Commented Mar 13, 2017 at 16:31

1 Answer 1

1

To find Object in an Array you can use .grep

searchArray = $.grep(fontSizeArray, function(n) {
    return n.element == $(y).prop("tagName").toLowerCase() && n.orginalSize == $(y).css("font-size") && n.size == $(y).css("font-size");
});

if(searchArray.length == 0){
    console.log("Not find");
}else{
    console.log("find");
}

.grep Finds the elements of an array which satisfy a filter function. The original array is not affected, and return an array.

I use all attributes to find the object, but you can use only tagName to find the element to avoid push duplicates.

You can see it here https://jsfiddle.net/egfg3dmc/3/

Sign up to request clarification or add additional context in comments.

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.