Reputation: 3
Is this possible to do using jQuery?
Lets say I have a list of items, with values attached eg:
How would I remove all duplicates and add the integers from removed duplicates to one entry, with an output as such using jQuery:
Edit: I've found a function to remove duplicates using $.each, but I have no idea where to go from here to store the values per iteration and modify the DOM for the original item.
var seen = {};
$('.variety_name').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).parent().remove();
else
seen[txt] = true;
});
Upvotes: 0
Views: 232
Reputation: 30099
Simple modification of the code you provided (with assumptions about the html):
<li class="item"><span class="name">Item1</span>: <span class="value">5</span></li>
<li class="item"><span class="name">Item2</span>: <span class="value">10</span></li>
<li class="item"><span class="name">Item3</span>: <span class="value">20</span></li>
<li class="item"><span class="name">Item2</span>: <span class="value">15</span></li>
<li class="item"><span class="name">Item4</span>: <span class="value">30</span></li>
<li class="item"><span class="name">Item2</span>: <span class="value">25</span></li>
<li class="item"><span class="name">Item1</span>: <span class="value">11</span></li>
var seen = {};
$('.name').each( function() {
var txt = $(this).text();
if (seen[txt] == undefined) {
seen[txt] = $(this);
} else {
var val = seen[txt].next('.value');
val.text( parseInt( val.text() ) + parseInt( $(this).next('.value').text() ) );
$(this).parent().remove();
}
});
When you haven't seen an item, store the object in seen
. When you have seen it, add current item's value to the stored object's value, and delete the current item.
Example: http://jsfiddle.net/JyGc9/
Upvotes: 1
Reputation: 1008
I don't know if there is an straight way to do it, but I can write something to accomplish that, I can use hash lists(tables) or inject the result straight into the dom; I will do using hash lists: I can format my HTML to look like:
<ol id="mainList">
<li><input type="hidden" value="5" name="item1"/> Item1: 5</li>
<li><input type="hidden" value="10" name="item2"/> Item2: 10</li>
<li><input type="hidden" value="20" name="item3"/> Item3: 20</li>
<li><input type="hidden" value="15" name="item2"/> Item2: 15</li>
...
</ol>
and my script :
function addDuplicates (){
var main_list = $('#mainList')
// Calculate the result list of items
var item_list = main_list .find('input');
var result = {}
item_list.each(function (index){
var list_name = $(this).attr('name')
var list_val = $(this).val()
if (typeOf(result[list_name])=='undefined')
result[list_name]=list_val
else
result[list_name]=result[list_name]+list_val
});
// render the result list
main_list.empty();
$.each (result, function (index){
main_list.append('<li><input type="hidden" value="'+result[index]+'" name="'+index+'"/>'+index+': '+result[index]+'</li>')
})
}
Upvotes: 0