Retrieving objects based on a property that begins with any element from an array

I have a collection of contacts that I need to filter based on the country code. Specifically, I want to identify contacts whose phone numbers start with any of the selected country codes.

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'm searching for an efficient one-line solution without using loops. So far, I've attempted:

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

However, this approach assumes the id parameter is an array and searches the entire number instead of just the beginning part. Is there a more effective way to filter the contacts based on whether their id starts with any of the values in the countries array?

Answer №1

You must go through each country and verify using the startsWith method.

const
    regions = ['54', '26', '33', '98'],
    allPeople = [{ id: '908787788', name: 'Sara' }, { id: '107564233', name: 'Mike' }, { id: '356765909', name: 'Sam' }, { id: '774567546', name: 'Lila' }];

console.log(allPeople.filter(({ id }) => regions.some(r => id.startsWith(r))));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Top method for developing a cohesive single-page application

Many websites are incorporating JSON data in string format within their page responses, along with HTML: For example, take a look at The benefit of rendering JSON in string format within the page response is that it allows for the efficient loading of da ...

Enable Class exclusively on upward scrolling on the browser

Is there a way to dynamically change the class of an element only when the user scrolls the browser page upwards? Issue Filide>> JavaScript $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll <= 100) { ...

Passing array map data to another screen in React Native

Greetings! I successfully created an array map to showcase specific data from my API. Now, I am faced with the challenge of TRANSFERRING THIS DATA TO ANOTHER SCREEN. My current dilemma lies in the fact that the displayed data is generated using ARRAY MAP, ...

Differences between JavaScript array manipulation using the split(" ") method and the spread operator

I'm currently attempting to determine if a given sentence is a palindrome, disregarding word breaks and punctuation. The code snippet that utilizes cStr.split(" ") DOES NOT achieve the desired outcome. Although it splits on whitespaces (&qu ...

JavaScript code to remove everything in a string after the last occurrence of a certain

I have been working on a JavaScript function to cut strings into 140 characters, ensuring that words are not broken in the process. Now, I also want the text to make more sense by checking for certain characters (like ., ,, :, ;) and if the string is bet ...

Issues encountered with asp.net javascript function not executing

Having trouble getting a javascript function to execute via jquery in an asp.net setting. Despite trying various approaches, the function doesn't run upon clicking the button. I've experimented with omitting jquery and using a static html input c ...

Guide to Inputting Numbers in a Form Field using a Pop-up Keypad (with Javascript/AJAX)

I am working on a small project that involves creating a keypad with buttons for all the digits, backspace, and decimal. When these buttons are clicked, they should populate a form field like a text box. The keypad will be located next to the form field as ...

Generating div elements of varying colors using a combination of Jinja templating and JavaScript loop

Utilizing jinja and javascript in my template, I am creating multiple rows of 100 boxes where the color of each box depends on the data associated with that row. For instance, if a row in my dataset looks like this: year men women 1988 60 40 The co ...

The cascading menu causes interference with the function of other elements in the

I am currently designing a navigation bar that includes a drop-down menu (with plans to add another one in the future). The issue I'm facing is that when the user clicks on the drop-down menu, it shifts all of the navigation links to the right. What I ...

Extracting information from a webpage by using Javascript to locate and interact

Seeking a way to retrieve the src attribute from an audio tag dynamically inserted into the DOM by third-party JavaScript without the ability to modify it. The goal is to back up these sounds by capturing their sources on the server side across multiple pa ...

Adding conditional href based on a specific criteria to an <a> tag in AngularJs

I have been working on a menu list where some menus contain URLs and others do not. When a menu item includes a URL, the href attribute is displayed, otherwise just the span tag is shown. I tried checking it like this but ended up with href="#" when the me ...

Incorporate a new JavaScript animation as the background for an established website, replacing the static background image

Seeking assistance with my portfolio as I delve into the world of Webdesign and learn the basics from templates. How can I integrate this javascript code into the background of my site, replacing the current minecraft image? Every attempt to implement it ...

Working with arrays of objects in D3.js using Javascript

Seeking guidance as I navigate through the world of javascript and D3.js. I have two distinct data sets (arrays of objects) that I hope to merge. My goal is to align the National Average Scores with the State Average Scores by matching the 'Answer&ap ...

Master the art of navigating the Windows Sound Recorder with the power of JavaScript

I am creating a project that involves controlling the Windows sound recorder for tasks such as starting, stopping, and saving recordings. Is there a way to do this without displaying the recorder window? I would appreciate any assistance in solving this. ...

Is Fetch executed before or after setState is executed?

I've encountered an issue while trying to send data from the frontend (using React) to the backend (Express) via an HTML form, and subsequently clearing the fields after submission. The code snippet below illustrates what I'm facing. In this scen ...

Ensure that all asynchronous code within the class constructor finishes executing before any class methods are invoked

Looking to create a class that takes a filename as a parameter in the constructor, loads the file using XmlHttpRequest, and stores the result in a class variable. The problem arises with the asynchronous nature of request.onreadystatechange, causing the ge ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

Smooth-scroll plugin does not activate active state (due to JS modification)

I'm currently facing an issue with a script that handles smooth scrolling and the active state on my main navigation. The plugin in question can be found at: It's important to note that the navigation bar is fixed and therefore has no height. T ...

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

Grab all the text using Java Jsoup

I am having an issue with the code I have written. The doc.body.text() statement is not displaying the text content within the style and script tags. I examined the .text() function code and found that it searches for all instances of TextNode. Can someone ...