0

I am trying to check if there is an id existing in an array, if the id is already there, then I will update that id's value. Otherwise I will push the id and its value into the array. How can I achieve that with jquery?

I have tried but it doesn't work, but double the size of the array

    $(itemData).each(function() {
        var name = $(this).data("name");
        var value = parseFloat($(this).data("amount"));

        if(dataArr.length == 0) {
            dataArr.push([name, value]);

        } else {
            $.each(dataArr, function(n, v) {
                if(name == n) {
                    v += value;
                }else {
                    dataArr.push([name, value]);
                }
            });
        }
    });

2 Answers 2

1

You are close, try the following:

$(function() {
  var itemData = $('.item-data'),
    dataArr = [];

  $(itemData).each(function() {
    var name = $(this).data("name");
    var value = parseFloat($(this).data("amount"));

    var found = false;
    $.each(dataArr, function(index, val) {
      if (!found && name == val[0]) {
        val[1] += value;
        found = true;
      }
    });
    if (!found) {
      dataArr.push([name, value]);
    }
  });

  console.log('dataArray = ', dataArr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item-data" data-name="name1" data-amount="1"></div>
<div class="item-data" data-name="name2" data-amount="2"></div>
<div class="item-data" data-name="name1" data-amount="3"></div>
<div class="item-data" data-name="name2" data-amount="4"></div>
<div class="item-data" data-name="name3" data-amount="5"></div>

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

Comments

1

I guess it would be easier with a hash (object literal), not an array:

var dataObj = {};
$(itemData).each(function() {
        var name = $(this).data("name");
        var value = parseFloat($(this).data("amount"));
        dataObj[name] = typeof dataObj[name] !== 'undefined' ? dataObj[name] + value : value;
});

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.