最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Oct 26, 2020 at 15:47 Ben_SBen_S 1131 gold badge2 silver badges5 bronze badges 2
  • if count is 0 for every object, should the function return true? – Simon Commented Oct 26, 2020 at 15:50
  • 1 What have you tried? Best to provide your attempts and say where you're getting stuck rather than simply ask for the answer. Especially since this looks like it might be a homework assignment. – Marc Commented Oct 26, 2020 at 15:52
Add a ment  | 

2 Answers 2

Reset to default 6

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;
}
发布评论

评论列表(0)

  1. 暂无评论