-1

I need the whole array of objects using an array of ids. I need to match it using contact_id. You may see expected output below

Array of objects (contacts)

[
    {
        "contact_id": 1,
        "f_name": "Hello",
    },
    {
        "contact_id": 2,
        "f_name": "YA",
    },
     {
        "contact_id": 3,
        "f_name": "Minion",
    },
     {
        "contact_id": 4,
        "f_name": "HALU",
    },
]

Array of ids (contacts2)

{
    "contact_ids": [
        "1",
        "2"
    ],
}

Expected Output

[
    {
        "contact_id": 1,
        "f_name": "Hello",
    },
    {
        "contact_id": 2,
        "f_name": "YA",
    },
]

Code

contacts.filter(item = > item.contact_id === contacts2)
1

3 Answers 3

1
contacts.filter(item => contacts2.contact_ids.some(id => id == item.contact_id));
Sign up to request clarification or add additional context in comments.

Comments

0

Steps:

  • Using Array#map on the contact_ids array to return a { contact_id: number, f_name: string } object for each one

  • Inside the mapping function use Array#find function to find the first contact that gets matched

  • Make sure to either use == instead of === or convert the string to a number before doing the check, since using === with a string and a number will always return false

var contacts = [{ "contact_id": 1, "f_name": "Hello" }, { "contact_id": 2, "f_name": "YA" }, { "contact_id": 3, "f_name": "Minion" }, { "contact_id": 4, "f_name": "HALU" }];

var contacts2 = { "contact_ids": [ "1", "2" ] };

var result = contacts2.contact_ids.map(function(id) {
  return contacts.find(function(contact) {
    // make sure to use `==` instead of `===` since you're comparing a string to a number
    return contact.contact_id == id;
  });
});
// You could also chain `.filter(Boolean)` if you wanted to discard the contacts that weren't found
console.log(result);

Comments

0

const items = [{
    "contact_id": 1,
    "f_name": "Hello",
  },
  {
    "contact_id": 2,
    "f_name": "YA",
  },
  {
    "contact_id": 3,
    "f_name": "Minion",
  },
  {
    "contact_id": 4,
    "f_name": "HALU",
  },
];

const ids = {
  "contact_ids": [
    "1",
    "2"
  ],
};

const filteredItems = items.filter(item => ids.contact_ids.includes(item.contact_id.toString()));

console.log(filteredItems)

2 Comments

How about some method. Is it fine?
Yeah, using some is totally fine. includes just seems more semantically correct to me for the current check and makes it easier to follow. Both options are completely fine. Just avoid comparing string and number with == as in the accepted answer as it is generally a bad habit which will bite you someday. Convert your types manually when you compare.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.