Add + 1 to the current number (Jquery)

1

Hello

The following function, 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 form ( 1 + 1 = 11 ) is being made.

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);
}
    
asked by anonymous 12.09.2017 / 16:29

2 answers

5

This happens when you mixes String and numbers with the + operator that is 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 do this 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
    
12.09.2017 / 16:33
3

The parameter must be arriving at function novo_id(lista) as string . Use the parseInt function 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);
}
    
12.09.2017 / 16:33