Add + 1 to current number (Jquery)

Asked

Viewed 371 times

1

Hello!

The following function below should add + 1 to id current, however, is not working, as opposed to adding, is adding + 1.

Example: If the current ID is 1, using the function, the next ID (1 + 1), should be 2; However the following is being done (1 + 1 = 11).

function novo_id(lista) {
    var id = 0;
	//console.log(id);
    if (lista.length > 0) {		
        for (var i = 0; i < lista.length; i++) {
            if (lista[i].id > id) {
                id = lista[i].id
			}
		}
        id = id + 1;
	}
    return (id == 0 ? 1 : id);
}

  • 1

    experiment id = Number(id) + 1;

2 answers

5


This happens when you mix String and numbers with the operator + sum but also concatenation. Javascript uses the operator as "sum" or as concatenation depending on the operands.

function novo_id(lista) {
  var id = 0;
  //console.log(id);
  if (lista.length > 0) {
    for (var i = 0; i < lista.length; i++) {
      var _id = Number(lista[i].id);
      if (_id > id) id = _id
    }
    id = id + 1;
  }
  return (id == 0 ? 1 : id);
}

console.log(novo_id([{id: '20'}]));

Another way to make it even simpler would be like this:

function novo_id(lista) {
  const ids = lista.map(el => Number(el.id));
  return Math.max.apply(Math, ids) + 1;
}

console.log(novo_id([{id: '230'}, {id: '10'}])); // 231

  • It works, but the other answer is cleaner. Thanks for the feedback.

  • @Wagnerson as you find it. The other answer is making type conversion here lista[i].id > id. That is to say String > Number. I don’t like it because it can make mistakes, hence my answer with Number() right at the beginning of the loop.

  • @Wagnerson joined another way. Cleaner than that is difficult :)

  • 1

    perfect this second. Thanks.

  • @Wagnerfilho se lista is empty you can use const ids = lista.map(el => Number(el.id)).concat(0);.

3

The parameter must be arriving in the function novo_id(lista) as string. Uses the function parseint before the sum:

function novo_id(lista) {
    var id = 0;
    //console.log(id);
    if (lista.length > 0) {     
        for (var i = 0; i < lista.length; i++) {
            if (lista[i].id > id) {
                id = lista[i].id
            }
        }
        id = parseInt(id) + 1;
    }
    return (id == 0 ? 1 : id);
}
  • 1

    It worked (Thank you)...

  • I’ll score, it’s because you’re still not allowing, I have to wait another minute.

  • 2

    Two suggestions: #1 - lista[i].id > id is forcing typing. It would be better to convert lista[i].id in Number prior to this comparison. #2 - If the lista[i].id come 08 in old browsers this will give other numbers.

  • @Sergio, just a doubt. And if there is no ID, it will have to start from 1, how can I do this with your method ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.