javascript - create array, use $.each to loop, and add value if not in array -
i have bunch of .defined in text , want create array of unique values javascript. basically, each anchor class defined, want first check array see if pair exists. if exists, go next anchor. if not exist, add array. code have tried using, not remove duplicate values.
var arr = new array(); y = 0; $("a.defined").each(function() { var spanishword = this.text; var englishword = this.title; if(spanishword in arr) { console.log("do nothing"); } else { arr.push({key: spanishword, value: englishword}); y++; }
for example, have these tags in text:
<a title="read">leer</a> <a title="work">trabajar</a> <a title="like">gustar</a> <a title="read">leer</a> <a title="sing">cantar</a> <a title="like">gustar</a>
and array like:
spanish word | english word leer read trabajar work gustar cantar sing
but instead looks like:
spanish word | english word leer read trabajar work gustar leer read cantar sing gustar
any ideas?
i in 2 steps.. 1 eliminate duplicates, , 1 create array:
var obj = {}; $('a.defined').each(function() { obj[this.text] = this.title; }); var arr = []; (var prop in obj) { if (obj.hasownproperty(prop)) arr.push({key: prop, value: obj[prop]}); }; console.log(arr);
if object sufficient , don't need array, stop after object created.
Comments
Post a Comment