简体   繁体   中英

How to check if Javascript array of objects has the same value throughout

I have the following array:
distributors = [{ Name: 'Foo', Count: 0}, { Name: 'Bar', Count: 0}, { Name: 'Baz', Count: 0}]

How do I check if the 'Count' is 0 for every object in the array? Ideally, I would like to write a function to return boolean if the value for 'Count' is 0 for every object in the array.

You can use every method. Every method checks if all elements in an array pass a test and returns true or false based on the function you have provided. So, If every element pass the test it returns true otherwise false.

 const distributors = [ { Name: 'Foo', Count: 0 }, { Name: 'Bar', Count: 0 }, { Name: 'Baz', Count: 0 }, ]; const ret = distributors.every((x) => x.Count === 0); console.log(ret);

This function returns true if all the Count property is 0

function checkCount(distributors) {
    for (let element of distributors) {
        if (element.Count) {
            return false;
        }
    }

    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM