Q:

How to avoid adding duplicate array entry and instead update the already existing entry

I have something like cart , and user can add desire products to own cart (here is cart is an array), but I want to prevent add duplicate id, instead add it as new value call q that show how many times user selected same product. I tried below for loop but no success.

var cart = [];
var i = 1;

$('li').click(function() {
  product = {};

  var id = $(this).data('id');
  product["id"] = id;

  $.each(product, function(i, v) {
    if (v.id == id) {
      console.log('dup');
     //product["q"] = i++;
    } else {
      console.log('not dup');
      //product["id"] = id;
    }
  });

  cart.push(product);
  console.log(cart);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li data-id="1">Product 1</li>
  <li data-id="2">Product 2</li>
  <li data-id="3">Product 3</li>
  <li data-id="4">Product 4</li>
</ul>

The goal array should be like this:
var cart = [
{id: 1},
{id: 2},
{id: 3},
{id: 4, q: 5} // q is set because user selected id num 4, five times
];

A:

Why not create an object you reference by ID instead so you don't have to find the (possibly-matching) item each time?

const cart = {};
$('li').click(function(e) {
  const id = e.target.dataset.id;
  if (!cart[id]) cart[id] = {
    id,
    clickCount: 0,
  }
  cart[id].clickCount++;
  console.log(cart);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li data-id="1">Product 1</li>
  <li data-id="2">Product 2</li>
  <li data-id="3">Product 3</li>
  <li data-id="4">Product 4</li>
</ul>

