tinyCoder
tinyCoder

Reputation: 360

Filter object by property that starts with any of array elements

I have an object of contacts where I need to filter by the country code, for which I need to check if the ID of the contact (phone number) starts with any of the selected country codes array.

var countries = ['1', '91', '55', '972'];

var allContacts = [
        {
            id: '9123242135321',
            name: 'Harun'
        },
        {
            id: '905366365289',
            name: 'Koray'
        },
        {
            id: '135366365277',
            name: 'Hayo'
        },
        {
            id: '963923824212',
            name: 'Bahaa'
        },
        {
            id: '513324515689',
            name: 'Hassan'
        }];

I am looking for an efficient one-line solution without looping, so what I have tried before is:

allContacts.filter(c => c.id.some(l => countries.includes(l)));

But that worked if the id parameter is an array, and it searches the whole number instead of the beginning, what is the efficient way to filter the contacts which their id key startsWith any of the countries array values?

Upvotes: 0

Views: 201

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You need to iterate the countries and check with startsWith.

const
    countries = ['1', '91', '55', '972'],
    allContacts = [{ id: '9123242135321', name: 'Harun' }, { id: '905366365289', name: 'Koray' }, { id: '135366365277', name: 'Hayo' }, { id: '963923824212', name: 'Bahaa' }, { id: '513324515689', name: 'Hassan' }];

console.log(allContacts.filter(({ id }) => countries.some(c => id.startsWith(c))));

Upvotes: 3

Related Questions