I've assumed that id
s are meant to be unique here. some
is a great function for checking the existence of things in arrays:
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];_x000D_
_x000D_
function add(arr, name) {_x000D_
const { length } = arr;_x000D_
const id = length + 1;_x000D_
const found = arr.some(el => el.username === name);_x000D_
if (!found) arr.push({ id, username: name });_x000D_
return arr;_x000D_
}_x000D_
_x000D_
console.log(add(arr, 'ted'));
_x000D_