Home > Back-end >  Determine if all object properties are equal
Determine if all object properties are equal

Time:07-09

I am creating the boolean hasMultipleCoverageLines to determine if different coverageLineName values exist on the items within coverageLines. Is there a way to simplify this expression so i don't have to explicitly check for each coverageLineName?

this.hasMultipleCoverageLines = !this.coverageLines.every((x) => x.coverageLineName === "Medical")
        && !this.coverageLines.every((x) => x.coverageLineName === "Dental")
        && !this.coverageLines.every((x) => x.coverageLineName === "Vision")
        && !this.coverageLines.every((x) => x.coverageLineName === "Life");

CodePudding user response:

A set will enforce uniqueness. Put the names in a set, and see if the count > 1.

let names = this.coverageLines.map(x => x.coverageLineName);
let set = new Set(names);
this.hasMultipleCoverageLines = set.size > 1;

With this ["Dental", "Dental", "Dental"] will produce a set of size 1, but ["Dental", "Vision", "Dental"] will produce a set of size 2, and so on...

CodePudding user response:

You could just check if any line is different than previous.

const hasMultipleCoverageLines = (lines) => {
  return lines.some((line, i) => {
    return i > 0 && line.coverageLineName !== lines[i - 1].coverageLineName;
  });
};
  • Related