How do I check if my array contains only one distinct element? `
var arr = [1, 1, 1];
var arr2 = [1, 2, 3];
checkIfThereIsOnlyOneElement(arr); //should return true
checkIfThereIsOnlyOneElement(arr2) //should return false;`
How do I check if my array contains only one distinct element? `
var arr = [1, 1, 1];
var arr2 = [1, 2, 3];
checkIfThereIsOnlyOneElement(arr); //should return true
checkIfThereIsOnlyOneElement(arr2) //should return false;`
Use Set object:
var arr = [1, 1, 1],
arr2 = [1, 2, 3],
checkForOne = function(arr){
return (new Set(arr)).size === 1;
}
console.log(checkForOne(arr));
console.log(checkForOne(arr2));
You could implement it this way:
var arr = [1, 1, 1];
var arr2 = [1, 2, 3];
console.log(checkIfThereIsOnlyOneElement(arr));
console.log(checkIfThereIsOnlyOneElement(arr2));
function checkIfThereIsOnlyOneElement(arr) {
arr.sort();
return arr[0] == arr[arr.length -1]
}
try this simple implementation
function checkIfThereIsOnlyOneElement(arr)
{
var map = {};//create a map
for( var counter = 0; counter < arr.length; counter++)
{
map[ arr[ counter ] ] = true;
if ( Object.keys ( map ).length > 1 ) //check if this map has only one key
{
return false;
}
}
return true;
}
simply check if all elements contain the same value, one way is to use "uniq" function of "lodash" module:
checkIfThereIsOnlyOneElement(arr){
return _.uniq(arr).length == 1;
}
You can check unique values in array. Based on this term we can implement your function:
var arr = [1, 1, 1];
var arr2 = [1, 2, 3];
function checkIfThereIsOnlyOneElement(arr) {
return arr.filter(function (item, i, ar) {
return ar.indexOf(item) === i;
}).length === 1;
}
console.log(checkIfThereIsOnlyOneElement(arr));
console.log(checkIfThereIsOnlyOneElement(arr2));
There are plenty of pretty easy implementations for this function. Let me give you two, one is a functional one-liner, the other is an iterative (probably better performing) snippet.
By the way, your naming is very bad, it should be called: isArrayOfTheSameElements
// Iterative:
function isArrayOfTheSameElements(arr){
var firstElement = arr[0];
for(var i=1; i < arr.length; i++){
if (arr[i]!==firstElement) {
return false;
}
}
return true;
}
// Functional:
function isArrayOfTheSameElements(arr){
return Object.keys(arr.reduce(function(current, next){
return current[next] = next && current;
}, {})).length <= 1;
}
You could use Array#every
and check only agsindt the firsr element.
function checkDistinct(array) {
return array.every(function (a, _, aa) { return a === aa[0]; });
}
var arr = [1, 1, 1],
arr2 = [1, 2, 3];
console.log(checkDistinct(arr)); // true
console.log(checkDistinct(arr2)); // false
You can always properly do like .every()
as pointed out by @Nina Scholz but for a variety you may also do like;
var all = a => a.length-1 ? a[0] === a[1] && all(a.slice(1)) : true;
console.log(all([1,1,1,1]));
console.log(all([1,1,1,2]));
It has the same benefit to cut the iteration once it meets a false
value.