确定数组是否包含JavaScript中指定值以外的任何内容?

时间:2019-03-12 05:21:45

标签: javascript arrays

我正在尝试编写一个函数,该函数可以检查数组中是否存在指定的值以及数组中是否存在除指定值之外的其他值。我正在寻找一种现代的解决方案,不需要向后兼容。

例如:

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

现在,如何检查是否存在除1以外的其他内容?

我尝试操纵函数参数值,例如:

valExists(array, !1); // returns false, i want 'true'

解决方案

我已经集成了我接受的答案提供的解决方案,如下所示:

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}`);};

结果是:

existUnique(array, 1); // true: false
existUnique(array2, 1); // true: true

7 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.every()

  

every()方法测试array中的所有元素是否通过由提供的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

答案 1 :(得分:1)

您返回带有两个键containsValuecontainOthers的对象,它们将具有boolean。 containsValue的值将通过使用includes来确定,而containOthers的值可以使用过滤器并检查返回数组的长度来确定

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

答案 2 :(得分:1)

您可以结合使用some()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));

但是最快(取决于输入)实际上可能是从中创建一个Set

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

答案 3 :(得分:0)

您只需要检查数组的长度,如果数组包含该值并且数组的长度大于1,则意味着该值在数组上并且在数组上也存在其他:)< / p>

答案 4 :(得分:0)

为此,我将使用Array.prototype.some(),如果在数组对象内的任何位置出现1,则以下内容将返回true。

  

some()方法测试数组中的至少一个元素是否通过了由提供的函数实现的测试。

const array = [1,1,1,2,3];

const hasOne = function(element) {
  return element === 1;
};

console.log(array.some(hasOne)); // true

或存在除1之外的任何东西。

const array = [1,1,1,2,3];

const noOne = function(element) {
  return element !== 1;
};

console.log(array.some(noOne)); // true

答案 5 :(得分:0)

您可以使用过滤器并比较原始数组和过滤后的数组的长度

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)

答案 6 :(得分:0)

这取决于您的输入。如果您的输入仅包含原始值,则use可以使用某些方法,例如Array.prototype.some()Array.prototype.includes()。其他人已经使用它们给了您答案。

我的补充是,如果您的数组包含文字对象或数组,则这些方法将无法按预期工作。在这种情况下,如果需要数组和对象,则需要编写自己的测试。阅读此answer

奖金:这是我比较两个数组/对象的解决方案

// 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;
}