0

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 compatibility 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
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every – Teemu Mar 12 '19 at 05: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 Mar 12 '19 at 07:52

7 Answers7

6

You can use Array.prototype.every()

The every() method tests whether all elements in the array pass the test implemented by the provided function

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
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
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
jaredrethman
  • 512
  • 5
  • 16
1

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));
brk
  • 48,835
  • 10
  • 56
  • 78
  • What is the use of the `reduce` here? You are literrally not using `curr` at all. This should be a big red flag that you are doing something wrong. (Hint: you just need to return `{ containsValue: arr.includes(val), containOthers: arr.filter(item => item !== val).length > 0 ? true : false }` out of the reduce function, instead of calling it `array.length` times. – Kaiido Mar 12 '19 at 05:46
1

You could use some() in combination 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));
Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

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 :)

Augusto Monteiro
  • 471
  • 1
  • 3
  • 16
  • 4
    `["me not agree", "me not agree", "me not agree"]` – Kaiido Mar 12 '19 at 05:29
  • This would work if it was a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), but OP is asking about an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). Also, @Kaiido clever, lol – Brian Adams Mar 12 '19 at 05:34
0

You can use filter and compare 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)
sumit
  • 15,003
  • 12
  • 69
  • 110
0

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 compare two array/object

// Own way to compare two array
// Compare only the object itself and all element inside.
// Not compare 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 compareSinglePropertyObject(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 && compareArray(firstObject[propOfFirst], secondObject[propOfSecond]);
                } else {
                    let arrayConvertedFirst = convertObjectToArrayOfSinglePropertyObject(firstObject[propOfFirst]);
                    let arrayConvertedSecond = convertObjectToArrayOfSinglePropertyObject(secondObject[propOfSecond]);
                    return propOfFirst === propOfSecond && compareArray(arrayConvertedFirst, arrayConvertedSecond);
                }
            }
        }
    }
}

//***Compare two objects
function compareObject(firstObject, secondObject) {
    let first = convertObjectToArrayOfSinglePropertyObject(firstObject);
    let second = convertObjectToArrayOfSinglePropertyObject(secondObject);
    return compareArray(first, second);
}

//***Compare two array
function compareArray(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 (!compareArray(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 (!compareSinglePropertyObject(firstObjectArray[0], secondObjectArray[0])) {
                        return false;
                    }
                } else {
                    if (!compareArray(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 (compareArray(element, secondArray[i])) {
                        return false;
                    }
                } else if (compareObject(element, secondArray[i])) {
                    return false;
                }
            } else {
                if (element === secondArray[i]) {
                    return false;
                }
            }
        }
        return true;
    });
    return arr;
}
kunquan
  • 1,127
  • 1
  • 10
  • 24