Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check array have same values in typescript

Trying to find array have same values or not in typescript but not working. So, How to findout. If anyone knows please help to find the solution.

app.component.ts:

  arr1 = ['1256','1256','1256'];
  arr2 = ['1256','8259','1256'];
  newArr=[];

 checkVal(val){
 val.forEach(x=>{ 
   this.newArr.push(x); 
 });

 if(this.newArr){
  alert("All the values are same in the array")
 }else{
  alert("No Diffent values are there in this array")
  } 
 }

 checkValApply1(){
  this.checkVal(this.arr1)
 }

 checkValApply2(){
  this.checkVal(this.arr2)
 }

Demo: https://stackblitz.com/edit/angular-ivy-9xyxxm?file=src%2Fapp%2Fapp.component.ts

like image 214
EMahan K Avatar asked Nov 25 '25 03:11

EMahan K


1 Answers

We can use the every function, since we check that the first value of the array is equal to the following, and it can be applied as follows:

checkVal(val) {
    const firstValue = val[0];
    const isSame = val.every((x) => x === firstValue);

    if (isSame) {
      alert('All the values are same in the array');
    } else {
      alert('No Diffent values are there in this array');
    }
  }
like image 130
Andriu1510 Avatar answered Nov 27 '25 16:11

Andriu1510



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!