valentincognito
11/2/2016 - 2:16 AM

Arrays Manipulation

Arrays Manipulation

/* Check if an array already contains the same element (name) */
var addNewElement = function(arr, newElement) {
	var found = false;
	for(var i=0; element=arr[i]; i++) {
		if(element.name == newElement.name) {
			found = true;
			if(newElement.population === 0) {
				arr[i] = false;
			} else {
				arr[i] = newElement;
			}
		}
	}
	if(found === false) {
		arr.push(newElement);
	}
	var newArr = [];
	for(var i=0; element=arr[i]; i++) {
		if(element !== false) newArr.push(element);
	}
	return newArr;
}