Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  178] [ 2]  / answers: 1 / hits: 6867  / 11 Years ago, fri, january 31, 2014, 12:00:00

Okay, I've tried several examples found on stackoverflow on my example and nothing worked for me as I wanted. I have an array with 12 object in it which looks like this



var buttons = [ {tag:adr,color:#123456},
{tag:ag,color:#123456},
{tag:fax,color:#123456},
{tag:ind,color:#123456},
{tag:sname,color:#123456},
{tag:per,color:#123456},
{tag:tel,color:#123456},
{tag:url,color:#123456},
{tag:url,color:#123456},
{tag:weblink,color:#123456},
{tag:weblink,color:#123456},
{tag:close,color:#123456} ];


and I wanna push this to another array var buttonsP if it is not in that array already. I tried (among other examples) with jquery .grep option:



var buttonsP =[];

for (var i = 0; i < buttons.length; i++){

var newObject = { valueTagP: buttons[i].tag, colorTagP: buttons[i].color };
if( $.grep(buttonsP, function(obj) { return obj.valueTagP != buttons[i].tag; }) ){
buttonsP.push(newObject);
}
}

for (var i = 0; i < buttonsP.length; i++){
$(.list).append(<li>+ buttonsP[i].valueTagP + , + buttonsP[i].colorTagP +</li>);
}


But duplicates were not removed.



You can check and edit my situation here: http://jsfiddle.net/M4mA9/



What am I doing wrong?


More From » jquery

 Answers
15

$.grep will return the matched array based on the condition. You see the details at http://api.jquery.com/jquery.grep/



Your code should be like



    var newObject = { valueTagP: buttons[i].tag, colorTagP: buttons[i].color };   
var newArr = $.grep(buttonsP, function(obj) {
return obj.valueTagP === buttons[i].tag;
});
if(newArr.length === 0) {
buttonsP.push(newObject);
}


I modified your code and updated the fiddle


[#48188] Thursday, January 30, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brittanye

Total Points: 263
Total Questions: 94
Total Answers: 115

Location: Burkina Faso
Member since Thu, Dec 23, 2021
2 Years ago
;