var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';
// don't add used name
console.log('before usedname: ' + JSON.stringify(array));
tryAdd(usedname, array);
console.log('before newname: ' + JSON.stringify(array));
tryAdd(newname, array);
console.log('after newname: ' + JSON.stringify(array));
function tryAdd(name, array) {
var found = false;
var i = 0;
var maxId = 1;
for (i in array) {
// Check max id
if (maxId <= array[i].id)
maxId = array[i].id + 1;
// Don't need to add if we find it
if (array[i].username === name)
found = true;
}
if (!found)
array[++i] = { id: maxId, username: name };
}
Array.prototype.hasElement = function(element) {
var i;
for (i = 0; i < this.length; i++) {
if (this[i] === element) {
return i; //Returns element position, so it exists
}
}
return -1; //The element isn't in your array
};
<script>
var obj = [];
function checkName(name) {
// declarations
var flag = 0;
var len = obj.length;
var i = 0;
var id = 1;
// looping array
for (i; i < len; i++) {
// if name matches
if (name == obj[i]['username']) {
flag = 1;
break;
} else {
// increment the id by 1
id = id + 1;
}
}
// if flag = 1 then name exits else push in array
if (flag == 0) {
// new entry push in array
obj.push({'id':id, 'username': name});
}
}
// function end
checkName('abc');
</script>
function checkAndAdd(name) {
var id = arr.length + 1;
var found = arr.some((el) => {
return el.username === name;
});
if (!found) { arr.push({ id: id, username: name }); }
}
function number_present_or_not() {
var arr = [2, 5, 9, 67, 78, 8, 454, 4, 6, 79, 64, 688];
var found = 6;
var found_two;
for (i = 0; i < arr.length; i++) {
if (found == arr[i]) {
found_two = arr[i];
break;
}
}
if (found_two == found) {
console.log('number present in the array');
} else {
console.log('number not present in the array');
}
}
let persons = [ {"name" : "test1"},{"name": "test2"}];
if(persons.some(person => person.name == 'test1')) {
... here your code in case person.name is defined and available
}