Home > Back-end >  Check if all items in an object has the same value in Angular
Check if all items in an object has the same value in Angular

Time:04-21

I have this object as presented below, and I want to check if all prices under menuItem.menuVariation.price has the same value. How can I do it in Angular without doing *ngFor.

  "menuItem": [
    {
      .................
      "menuVariation": [
        {
          .................
          "price": 10
        },
        {
          .................
          "price": 11
        },
        {
          .................
          "price": 11
        }
      ]
    }
  ]

CodePudding user response:

pass menuVariation as parameter, below funcion return true if passed parameter price all are same value

IsPriceAllSame(val:any){

Const matchedItem=Val.filter((item)=>item.price==val[0].price);
      return matchedItem.length == val length;
}

CodePudding user response:

You could use the .every method on the menuVariation array that will test if all elements in the array will pass the predicate specified. So in your case you could test that all values matches the first value of the array, for in that case we know that all values are the same. Something like the following:

menuItem[0].menuVariation.every((element, idx, arr) => element.price === arr[0].price);

menuItem[0] - Here we access the first entry of the array
.menuVariation - The object containing the list of objects, this is the array we preform the .every method on
.every - Array method that takes 3 arguments, (element, index, array).

  1. Element parameter is each element of the array.
  2. Index is the index of each element.
  3. Array is the array we called the method upon, in our case the menuVariation array.

So with these in place we can now check if each element is the same as the arrays first element, if all matches it will return true otherwise false.

This is done with taking the element and access the price property and check against the array[0]th elements price property as follows:

element.price === arr[0].price

You can read more about the .every method here

  • Related