Fernando Urban Fernando Urban - 6 months ago 16
CSS Question

How I can separate and collect different values in a list of attributes in HTML with Javascript?

I have the next list:

<ul>
<li class="list" data="Paul" data-id="2">Paul</li>
<li class="list" data="Paul" data-id="4">Paul</li>
<li class="list" data="Peter" data-id="3">Peter</li>
<li class="list" data="Peter" data-id="1">Peter</li>
<li class="list" data="John" data-id="11">John</li>
<li class="list" data="John" data-id="12">John</li>
</ul>


So, the goal is get:

Paul: 6 | Peter: 4 | John: 23


I'm trying with a .map in jquery like:

$(function() {
var total = 0;
var counter = $('li.list').length;
$('#resp').html(counter);

var dataList = $("li.list").map(function() {
var data = $(this).attr('data')
return data+$(this).data("id");
}).get();

mydata = dataList.join(";");
alert(mydata)
});


And this is returning:

Paul2;Paul4;Peter3;Peter1;John11;John12


How can I sort and sum for separte for get:

Paul: 6 | Peter: 4 | John: 23


Thank you.

Answer

You could create Array with Array.from() and use reduce and return Object

var result = Array.from($('ul li')).reduce((obj, e) => {
  obj[$(e).data('name')] = (obj[$(e).data('name')] || 0) + parseInt($(e).data('id'));
  return obj;
}, {})

console.log(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="list" data-name="Paul" data-id="2">Paul</li>
  <li class="list" data-name="Paul" data-id="4">Paul</li>
  <li class="list" data-name="Peter" data-id="3">Peter</li>
  <li class="list" data-name="Peter" data-id="1">Peter</li>
  <li class="list" data-name="John" data-id="11">John</li>
  <li class="list" data-name="John" data-id="12">John</li>
</ul>

Comments