I'm trying to write a function that can check whether a specified value exists in an array and also whether a value other than what is specified exists in an array. I'm looking for a modern solution, no backwards patibility is required.
For example:
const array = [1,1,1,2,3];
// this checks whether a value exists
const valExists = (array, value) => array.includes(value);
valExists(array,1); // returns true
Now, how do I check whether anything other than 1 exists?
I've tried manipulating the function parameter value e.g:
valExists(array, !1); // returns false, i want 'true'
Solution
I've integrated the solution provided by my accepted answer as follows:
const array = [1,1,1,2,3];
const array2 = [1,1,1,1,1];
//this checks whether a value exists and also whether it is unique
function existUnique(array, value) { let a = array.includes(value); let b = array.every( e => e === value ); console.log(`${a}: ${b}`);};
The results are:
existUnique(array, 1); // true: false
existUnique(array2, 1); // true: true
I'm trying to write a function that can check whether a specified value exists in an array and also whether a value other than what is specified exists in an array. I'm looking for a modern solution, no backwards patibility is required.
For example:
const array = [1,1,1,2,3];
// this checks whether a value exists
const valExists = (array, value) => array.includes(value);
valExists(array,1); // returns true
Now, how do I check whether anything other than 1 exists?
I've tried manipulating the function parameter value e.g:
valExists(array, !1); // returns false, i want 'true'
Solution
I've integrated the solution provided by my accepted answer as follows:
const array = [1,1,1,2,3];
const array2 = [1,1,1,1,1];
//this checks whether a value exists and also whether it is unique
function existUnique(array, value) { let a = array.includes(value); let b = array.every( e => e === value ); console.log(`${a}: ${b}`);};
The results are:
existUnique(array, 1); // true: false
existUnique(array2, 1); // true: true
Share
Improve this question
edited Mar 12, 2019 at 8:51
N. Lawrence
asked Mar 12, 2019 at 5:21
N. LawrenceN. Lawrence
31 silver badge3 bronze badges
2
- developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Teemu Commented Mar 12, 2019 at 5:23
- Thanks all, these are all great solutions and I'm sure I'll use variations of these to solve other problems. For this problem I went with integrating the Array.prototype.every() method into my valExists function. Thanks Maheer and Teemu. – N. Lawrence Commented Mar 12, 2019 at 7:52
7 Answers
Reset to default 6You can use Array.prototype.every()
The
every()
method tests whether all elements in thearray
pass the test implemented by the providedfunction
const array = [1,1,1,2,3];
const array2 = [1,1,1,1,1];
console.log(array.every(x => x === 1)); //false
console.log(array2.every(x => x === 1)); //true
You could use some()
in bination of your valExists
:
const arr1 = [1, 1, 1, 1, 1];
const arr2 = [1, 2, 2, 1, 3];
const arr3 = [2, 2, 2, 5, 3];
const valExists = (array, value) => array.includes(value);
const valIsUnique = (array, value) =>
valExists(array, value) && !array.some(v => v !== value);
console.log('arr1', valIsUnique(arr1, 1));
console.log('arr2', valIsUnique(arr2, 1));
console.log('arr3', valIsUnique(arr3, 1));
But the fastest (depending on the input) might actually be creating a Set from it:
const arr1 = [1, 1, 1, 1, 1];
const arr2 = [1, 2, 2, 1, 3];
const arr3 = [2, 2, 2, 5, 3];
const valIsUnique = (array, value) => {
const set = new Set(array);
return set.size === 1 && set.has(value);
};
console.log('arr1', valIsUnique(arr1, 1));
console.log('arr2', valIsUnique(arr2, 1));
console.log('arr3', valIsUnique(arr3, 1));
I would use Array.prototype.some() for this, the below will return true if 1 appears anywhere inside your array object.
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function.
const array = [1,1,1,2,3];
const hasOne = function(element) {
return element === 1;
};
console.log(array.some(hasOne)); // true
OR anything other than 1 exists.
const array = [1,1,1,2,3];
const noOne = function(element) {
return element !== 1;
};
console.log(array.some(noOne)); // true
You return an object with two keys containsValue
& containOthers
which will have boolean . containsValue
value will be determined by use of includes
& containOthers
value can be determined using filter and checking the length of the returned array
const array = [1, 1, 1, 2, 3];
function valExists(arr, val) {
return {
containsValue: arr.includes(val),
containOthers: arr.filter(item => item !== val).length > 0 ? true : false
}
}
console.log(valExists(array, 1));
you just need to check the length of the array, if the array includes the value and the length of the array is more than 1 it means that the value is on the array and exists something else on the array too :)
You can use filter and pare the length of original and filtered array
const array = [1,1,1,2,3];
const array1 = [1,1,1,1,1]
console.log(array.filter(a=>a===1).length===array.length)
console.log(array1.filter(a=>a===1).length===array1.length)
It depends on your input. If your input include only primitive value, use can use some methods like Array.prototype.some() or Array.prototype.includes(). Other people already gave you the answer using them.
My addition is in case your array contain literal object or array, those methods will not work as expect. In this case you will need to write your own test in case of array and object. Read this answer
Bonus: This is my solution for pare two array/object
// Own way to pare two array
// Compare only the object itself and all element inside.
// Not pare constructor or prototypes of it
function checkObjectInsideOtherObject(child, parent) {
let parentArray = convertObjectToArrayOfSinglePropertyObject(parent);
let childArray = convertObjectToArrayOfSinglePropertyObject(child);
let arr = arrayDifference(childArray, parentArray);
return arr.length === 0;
}
// ***Convert an object to an array of single property objects
function convertObjectToArrayOfSinglePropertyObject(obj) {
let array = [];
for (let element in obj) {
array.push({ [element]: obj[element] });
}
return array;
}
//***Compare two object that have only one property each
function pareSinglePropertyObject(firstObject, secondObject) {
for (let propOfFirst in firstObject) {
for (let propOfSecond in secondObject) {
// Check type of property of object
if (typeof firstObject[propOfFirst] !== typeof secondObject[propOfSecond]) {
return false;
}
// Check key and value inside
// Note that the value can be an array or another object
else if (typeof firstObject[propOfFirst] !== "object" && typeof secondObject[propOfSecond] !== "object") {
return propOfFirst === propOfSecond && firstObject[propOfFirst] === secondObject[propOfSecond];
} else {
if (firstObject[propOfFirst] instanceof Array && secondObject[propOfSecond] instanceof Array) {
return propOfFirst === propOfSecond && pareArray(firstObject[propOfFirst], secondObject[propOfSecond]);
} else {
let arrayConvertedFirst = convertObjectToArrayOfSinglePropertyObject(firstObject[propOfFirst]);
let arrayConvertedSecond = convertObjectToArrayOfSinglePropertyObject(secondObject[propOfSecond]);
return propOfFirst === propOfSecond && pareArray(arrayConvertedFirst, arrayConvertedSecond);
}
}
}
}
}
//***Compare two objects
function pareObject(firstObject, secondObject) {
let first = convertObjectToArrayOfSinglePropertyObject(firstObject);
let second = convertObjectToArrayOfSinglePropertyObject(secondObject);
return pareArray(first, second);
}
//***Compare two array
function pareArray(firstArray, secondArray) {
if (firstArray.length !== secondArray.length) {
return false;
}
let arrayLength = firstArray.length;
for (let i = 0; i < arrayLength; i++) {
if (typeof firstArray[i] !== typeof secondArray[i]) {
return false;
}
// Check whether the element are object or not
// Note that array is object in return
// Check not array/object first
if (typeof firstArray[i] !== "object" && typeof secondArray[i] !== "object") {
if (firstArray[i] !== secondArray[i]) {
return false;
}
}
// Check nested array and nest object
if (typeof firstArray[i] === "object" && typeof secondArray[i] === "object") {
// nested array use recursive
if (firstArray[i] instanceof Array && secondArray[i] instanceof Array) {
if (!pareArray(firstArray[i], secondArray[i])) {
return false;
}
}
// Check for object nest inside using recursive
else {
let firstObjectArray = convertObjectToArrayOfSinglePropertyObject(firstArray[i]);
let secondObjectArray = convertObjectToArrayOfSinglePropertyObject(secondArray[i]);
if (firstObjectArray.length === 1 && secondObjectArray.length === 1) {
if (!pareSinglePropertyObject(firstObjectArray[0], secondObjectArray[0])) {
return false;
}
} else {
if (!pareArray(firstObjectArray, secondObjectArray)) {
return false;
}
}
}
}
}
return true;
}
// What elements that are in first array and not in second array
function arrayDifference(firstArray, secondArray) {
let secondArrayLength = secondArray.length;
let arr = firstArray.filter(element => {
for (let i = 0; i < secondArrayLength; i++) {
// Check special cases first
if (typeof element === "object" && typeof secondArray[i] === "object") {
if (element instanceof Array && secondArray[i] instanceof Array) {
if (pareArray(element, secondArray[i])) {
return false;
}
} else if (pareObject(element, secondArray[i])) {
return false;
}
} else {
if (element === secondArray[i]) {
return false;
}
}
}
return true;
});
return arr;
}