0

I have 2 arrays like the following:

Arr1 = [{"test":{"active":false},"id":1},{"test":{"active":true},"id":2}]

Arr2 = [{"test":{"active":true},"id":1},{"test":{"active":true},"id":2}]


 import { HttpClient } from '@angular/common/http';
 import { Injectable } from '@angular/core';
import { Observable, Subject, throwError } from 'rxjs';
  import { catchError, map } from 'rxjs/operators';

 getOverviewCards(): any {
 return this.http
  .get<OverviewCardList>(this.overviewCardUrl)
  .pipe(map(overviewCards => overviewCards.cardList))
  .pipe(catchError((error: any) => throwError(error)));
}


   this.Arr1.filter(element => this.Arr2.includes(element.test.active))

I know I did wrong, I am using typescript.

Now, I want to check 'active' variable in both arrays. That is, active in first object of arr1 with arr2 and so on. If the both arrays are same it should return true else false. In the above array examples it should return false.

Can anyone please help me with the quickest method. Thanks.

learner
  • 357
  • 1
  • 6
  • 16
  • What is the desired output? – Kobe Aug 12 '19 at 12:37
  • 1
    Welcome to SO. Please show us what you have tried. The objective here is for you to show your attempts to solve your own issue and people help you fix *your code* when it doesn't work as expected, not to write all the code for you – charlietfl Aug 12 '19 at 12:38
  • Hi Kobe disired output should be the true or false – learner Aug 12 '19 at 12:38
  • Possible duplicate of [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Heretic Monkey Aug 12 '19 at 13:01

2 Answers2

1

You can use every alongside map - map over each element and make sure all are true, otherwise, return false:

Arr1 = [{"test":{"active":false},"id":1},{"test":{"active":true},"id":2}]

Arr2 = [{"test":{"active":true},"id":1},{"test":{"active":true},"id":2}]

console.log(Arr1.every((o, i) => o.test.active === Arr2[i].test.active))
Kobe
  • 6,226
  • 1
  • 14
  • 35
  • `Arr1.every((o, i) => o.test.active === Arr2[i].test.active)` would be shorter or did I misunderstand your idea? – claasic Aug 12 '19 at 12:48
  • @assoron no, you are absolutely correct, nice one, ill sub that in :) – Kobe Aug 12 '19 at 12:50
-1

const arr1 = [{ "test": { "active": false }, "id": 1 }, { "test": { "active": true }, "id": 2 }]

const arr2 = [{ "test": { "active": true }, "id": 1 }, { "test": { "active": true }, "id": 2 }]

function check(one, two) {
    let same = true;
    one.forEach((el, index) => {
        if (one[index].test.active !== two[index].test.active) {
            same = false;
        }
    });
    return same
}

console.log(check(arr1, arr2))
Vadim Hulevich
  • 1,803
  • 8
  • 17