Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter values from array and object comparison in javascript?

Here, I have one object and one array I want to filter value comparing both array and object,

object have multiple values see in below code Reader, Author, Publisher.., in array Author and Reader I want to compare them and want this type of results of wanted result :- [1, 8] this is my object

object1 = { 1: "Reader"
  8: "Author"
  3: "Publisher"
  9: "Site Editor"
  11: "Guest"
  12: "Editor"
  13: "Designer"
  14: "Publicist"
}

this is my array

array1 = ["Reader", "Author"]
like image 368
Dharmesh Avatar asked Apr 23 '26 07:04

Dharmesh


2 Answers

You could filter the keys of the object and check if the key has a value in the array using includes

const object1 = {
  1: "Reader",
  8: "Author",
  3: "Publisher",
  9: "Site Editor",
  11: "Guest",
  12: "Editor",
  13: "Designer",
  14: "Publicist"
};

const array1 = ["Reader", "Author"]

const keys = Object.keys(object1).filter(k => array1.includes(object1[k]))

console.log(keys)
like image 57
adiga Avatar answered Apr 24 '26 21:04

adiga


You could take a Map and return the values by using the switched key/value from the entries of the object.

The result are strings, because the keys of an object are either strings or symbols.

var object = { 1: "Reader", 8: "Author", 3: "Publisher", 9: "Site Editor", 11: "Guest", 12: "Editor", 13: "Designer", 14: "Publicist" },
    array = ["Reader", "Author"],
    result = array.map(
        Map.prototype.get,
        new Map(Object.entries(object).map(([k, v]) => [v, k]))
    );

console.log(result);
like image 25
Nina Scholz Avatar answered Apr 24 '26 21:04

Nina Scholz



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!