JenMorgan / js-learning

0 stars 0 forks source link

Write function that returnes true if all elements in array are of a specified value #60

Open kartamyshev opened 4 years ago

kartamyshev commented 4 years ago

Example:

fn([2, 2, 2, 2], 2) // true
fn([2, 12, 2, 2], 2) // false
JenMorgan commented 4 years ago

function allValuesAreEqualTo (arr, value) {
    let result = true;
    for (const item of arr) {
        if (item !== value) {
            result = false;
            break;
        }
    }
    return result;
}
JenMorgan commented 4 years ago
function allValuesAreEqualTo (arr, value) {
    let counter = arr.reduce((result, current) => { 
        (current === value) ? result++ : result;
        return result;
    }, 0);
    return (counter === arr.length) ? true : false;
}
console.log(allValuesAreEqualTo([2, 2, 2, 2], 2));