webbydevy
webbydevy

Reputation: 1220

Compare array of ints with Array of Objects and return property

Given the following array of objects:

var arrayOfObjs = [{
    id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0",
    typeID: 2
  },
  {
    id: "270d8355-d8b6-49c4-48ac-97a44422c705",
    typeID: 3
  },
  {
    id: "sdks7878-d8b6-49c4-48ac-97a44422c705",
    typeID: 4
  }
];

And an Array of Ints:

var arrayOfInts = [2, 4];

How would I compare the two and return an array of IDs if the array of ints matches the arrayOfObjects.

The return should be:

var matchingIDs = [
    "d8eed6df-9f12-47d4-5b71-3352a92ebcf0", 
    "sdks7878-d8b6-49c4-48ac-97a44422c705"
];


var missingIDs = ["270d8355-d8b6-49c4-48ac-97a44422c705"];

Upvotes: 1

Views: 56

Answers (3)

Ori Drori
Ori Drori

Reputation: 191976

With lodash you can achieve this using a chain with _.keyBy(), _.at(), and _.map():

var arrayOfObjs = [{"id":"d8eed6df-9f12-47d4-5b71-3352a92ebcf0","typeID":2},{"id":"270d8355-d8b6-49c4-48ac-97a44422c705","typeID":3},{"id":"sdks7878-d8b6-49c4-48ac-97a44422c705","typeID":4}];

var arrayOfInts = [2, 4];

var result = _(arrayOfObjs)
  .keyBy('typeID') // get a dictionary of objects by their type ids
  .at(arrayOfInts) // get the objects that matches the array of ints
  .map('id') // map each object to the id
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 0

Idan Beker
Idan Beker

Reputation: 363

Many ways to accomplish this, I chose map\filter usage since javascript is a functional language.

const allItems = [{
    id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0",
    typeID: 2
  },
  {
    id : "270d8355-d8b6-49c4-48ac-97a44422c705",
    typeID: 3
  },
  {
    id : "sdks7878-d8b6-49c4-48ac-97a44422c705",
    typeID: 4
  }];

const validIds = [2, 4];

const filteredItems = allItems
                      .filter(({typeID})=> validIds.includes(typeID))
                      .map(({id})=>id)

console.log(filteredItems)

Upvotes: 1

Faly
Faly

Reputation: 13346

Use array.prototype.filter, array.prototype.includes and array.prototype.map

var datas = [{
    id: "d8eed6df-9f12-47d4-5b71-3352a92ebcf0",
    typeID: 2
  },
  {
    id : "270d8355-d8b6-49c4-48ac-97a44422c705",
    typeID: 3
  },
  {
    id : "sdks7878-d8b6-49c4-48ac-97a44422c705",
    typeID: 4
}];

var arrayOfInts = [2, 4];

var matchingIDs = datas.filter(d => arrayOfInts.includes(d.typeID)).map(e => e.id);

var missingIDs= datas.filter(d => !arrayOfInts.includes(d.typeID)).map(e => e.id);

console.log('matchingIDs: ', matchingIDs);
console.log('missingIDs: ', missingIDs);

Upvotes: 3

Related Questions