learnbydoing
learnbydoing

Reputation: 499

Javascript - Get a corresponding object between two arrays

I have the following arrays:

First array:

const dummyJSON = [
    {
      id: 1,
      sponsor_date: '2020-08-16T22:45:03.154Z'
    },
    {
      id: 2,
      sponsor_date: '2020-09-16T22:45:03.154Z'
    },
    {
      id: 3,
      sponsor_date: '2020-09-01T22:45:03.154Z'
    }
  ]

Second array:

const validated = [ true, false, false ]

And I wanted to get the object (dummyJSON.id) when the corresponding (validated) array item is true.

Basically, if the first item in the validate [0] array has a value of "true", then I would like to have the corresponding [0] item's id value in the dummyJSON array.

Upvotes: 3

Views: 98

Answers (3)

ray
ray

Reputation: 27275

If your goal is just to get the validated items, use filter:

const valid = dummyJSON.filter((item, index) => validated[index]);

If you just want the ids, add a map call:

const valid = dummyJSON.filter((item, index) => validated[index]);
const ids = valid.map(x => x.id);

This could be done in a single line if you prefer, by chaining the map call:

const ids = dummyJSON.filter((item, index) => validated[index]).map(x => x.id);

const dummyJSON = [
    { id: 1, sponsor_date: '2020-08-16T22:45:03.154Z' },
    { id: 2, sponsor_date: '2020-09-16T22:45:03.154Z' },
    { id: 3, sponsor_date: '2020-09-01T22:45:03.154Z' }
];

const validated = [ true, false, false ];

// source objects
console.log(dummyJSON.filter((_, index) => validated[index]));

// just the ids
console.log(dummyJSON.filter((_, index) => validated[index]).map(x => x.id));

Upvotes: 2

kind user
kind user

Reputation: 41893

You can use Array#reduce to get array of validated ids.

It will basically loop over every element and if the index of currently iterated object corresponds to the truthy value inside validated with the very same index, the object's id will be pushed to the result.

const dummyJSON = [
    { id: 1, sponsor_date: '2020-08-16T22:45:03.154Z' },
    { id: 2, sponsor_date: '2020-09-16T22:45:03.154Z' },
    { id: 3, sponsor_date: '2020-09-01T22:45:03.154Z' }
];

const validated = [true, false, false];

const validatedIds = dummyJSON
  .reduce((s, { id }, i) => (validated[i] ? s.push(id) : s, s), []);

console.log(validatedIds);

Upvotes: 2

Goran.it
Goran.it

Reputation: 6299

No need for reduce, filter can do that just as well and faster :

const validated = [ true, false, false ]
const dummyJSON = [
    {
      id: 1,
      sponsor_date: '2020-08-16T22:45:03.154Z'
    },
    {
      id: 2,
      sponsor_date: '2020-09-16T22:45:03.154Z'
    },
    {
      id: 3,
      sponsor_date: '2020-09-01T22:45:03.154Z'
    }
  ]
// To get all validated objects from dummy JSON
const validatedJSON = dummyJSON.filter((obj, index) => validated[index])
// To extract just the ID's
const validatedJSONIds = validatedJSON.map(json => json.id)

Upvotes: 0

Related Questions