Get items from an array that have a property matching another array

Is there a more efficient way to create a new array with contact objects that have values matching those in selectedContact?

selectedContact: number[] = [0,2] //value
contacts: Contact[] = [{ 
  firstName:"Dan";
  lastName:"Chong";
  email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e682878885a68b878f8ac885898b">[email protected]</a>";
  value:0;
},
{ 
  firstName:"Mark";
  lastName:"Wong";
  email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="157874677e625578747c793b767a78">[email protected]</a>";
  value:1;
},
{ 
  firstName:"Layla";
  lastName:"Sng";
  email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e222f37222f0e232f2722602d2123">[email protected]</a>";
  value: 2;
}]

Desired output:

newArray = [{ 
 firstName:"Dan";
 lastName:"Chong";
 email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2440454a476449454d480a474b49">[email protected]</a>";
 value:0;
},{ 
 firstName:"Layla";
 lastName:"Sng";
 email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a161b03161b3a171b131654191517">[email protected]</a>";
 value:2;
}];

Current approach:

const newArray: Contact[] = [];
this.selectedContact.forEach(index => {
  newArray.push(this.contacts.find(c => c.value === index));
});

Answer №1

When it comes to efficiency, it is more advantageous to iterate through the selectedContacts instead of the contacts. This is because contacts are indexed as an array and you are accessing them by index.

Let's assume the length of contacts is N and the length of selectedContacts is M.

Since selectedContacts is a subset of contacts, we can infer that M <= N. For larger databases of contacts, this disparity can have a significant impact.

The provided code:

this.selectedContact.forEach(index => {
  newArray.push(this.contacts.find(c => c.value === index));
});

Runs in O(M*N) complexity since it loops through selectedContact (O(M)) and each time has to search for a value in contacts (O(N)).

The suggested solution traverses contacts (O(N)) and checks for a value in selectedContact which is O(M). Thus, the algorithm is essentially O(N*M).

In your scenario, you already possess a straightforward method of finding contacts by number due to the indexed nature of contacts.

This enables you to utilize code like this:

return this.selectedContact.map(index => this.contacts[index]);

As retrieving an array element by index operates in O(1) time complexity, this approach is most efficient with a O(M) scale.

If you cannot rely on array indexing, alternative data structures such as a Map where the id serves as the key and contact as the value can offer similar swift look-up speeds (approximately O(1)).

Answer №2

You should consider utilizing the Array.prototype.filter() method for your solution.

When used, the filter() function generates a new array containing elements that meet the criteria set by the provided function.

Another useful method is Array.prototype.includes()

The includes() function helps determine whether a particular element is present in an array, returning either true or false accordingly.

To see it in action, here's a snippet of code:

var selectedContact = [0,2];
var contacts = [{ 
  firstName: "Dan",
  lastName: "Chong",
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d595c535e7d505c5451135e5250">[email protected]</a>",
  value: 0
},
{ 
  firstName: "Mark",
  lastName: "Wong",
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c616d7e677b4c616d6560226f6361">[email protected]</a>",
  value: 1
},
{ 
  firstName: "Layla",
  lastName: "Sng",
  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6bab7afbab796bbb7bfbaf8b5b9bb">[email protected]</a>",
  value: 2
}]
let newArray =  contacts.filter(c => selectedContact.includes(c.value));

console.log(newArray);

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

Add to Firebase reference using AngularFire

Imagine I'm constructing a never-ending scroll of articles. The article's ID is obtained from the URL: var id = $stateParams.id; I aim to startAt that specific index in my Firebase collection and restrict it to 10 items: var limit = 10; var a ...

What could be causing the lack of updates in my SolidJS component when the data changes?

One of my components in SolidJS is an Artist page component. Here is a snippet of the code: export function Artist() { const params = useParams<{ id: string }>(); const [data, setData] = createSignal(null); createEffect(() => { fetchArti ...

Utilize webpack to import functions from separate files

I am looking to streamline the process of importing and using functions from a different file. Ideally, I would like to simply call these functions by their name without any extra prefixes or naming conventions. However, I am aware that using eval() can po ...

What is the best way to update an object with a new object using JavaScript or lodash?

My data structure is as follows: const data = { getSomething: { id: '1', items: [ { id: '1', orders: [ { id: '1', ...

What is the best way to dynamically generate and update the content of a select input in an Angular form using reactive programming techniques?

I have successfully developed an Angular reactive form that includes a select field populated dynamically with values retrieved from an API call. In addition, I have managed to patch the form fields with the necessary data. My current challenge is to dyn ...

Accessing multi-dimensional array properties in PHP with JavaScript integration

In my PHP code, I have an array structured like this: <?php $data = array(); $data[0] = array('year' => 2001, 'month' => array( 'January' => array('val1' => 1000, 'v ...

Troubleshooting a JavaScript Error on an ASP.NET MasterPage

After implementing the following JavaScript code: <script type="text/javascript> $(document).ready(function () { $('#social-share').dcSocialShare({ buttons: 'twitter,facebook,linkedin,di ...

Tips for enhancing contrast in MUI dark theme modals

Currently, I am implementing MUI dark mode for my Next.js application. While the MUI modal functions perfectly in light mode, I am struggling with visibility issues when using it in dark mode. The contrast is not strong enough, making it difficult to disti ...

What are the reasons for the inability to send form-data in Postman?

Encountering an issue when trying to send form-data in postman as Sequelize returns an error: value cannot be null However, everything works fine when sending a raw request with JSON. Have tried using body-parser and multer, but no luck. This is my inde ...

Tips for adjusting the duration of a background in jQuery

jQuery(document).ready(function(){ jQuery('div').css('background-color','#ffffff').delay(12000).css('background-color','#000000'); }); Hello everyone! I'm having some trouble with this code. I am ...

Integrating a fictitious style using jQuery

Having some trouble with this code snippet. The issue arises when trying to apply the following style using jQuery. CSS .arrow_box { position: absolute; width: 24px; border-radius: 30px 30px 3px 3px; height: 17px; float:left; } .arrow_box:after { bord ...

Tips for inserting a DIV and SCRIPT from a single HTML template into a webpage

I'm working with an HTML template that contains a DIV with a button and a script with a function to call when the button is clicked: <div id="CLC_Form"> various text and checkbox inputs go here... <br> <input type="button" ...

While Advanced REST Client successfully retrieves an infinite JSON file from the AngularJS REST service, Postman encounters an error with the code ERR_INCOMPLETE_CHUNKED_ENCODING

I've encountered a peculiar issue. When making a REST call in Angular (using an app built with Ionic v1) to a Java endpoint, something goes awry and Chrome throws the following error: https://i.sstatic.net/1sxp7.png The code of interest is this Angul ...

Finding strikeout text within <s> or <del> tags can be identified by closely examining the HTML codes

The issue arises with the text that reads as follows: 316.6.1 Structures. Structures shall not be constructed This is represented in HTML as: <b> <s> <span style='font-size:10.0pt'>316.6.1 Structures</span> ...

Displaying items from an array is made easy thanks to the combination of mapGetters, VUEJS, vuex, and vuetify

My website has two main routes: one for the home page and another for a configuration panel. In the home page, there is a container displaying information such as date, time, current temperature, etc. Below that, there is another container where users can ...

What are the reasons for the slower runtime of node.js compared to the Google Chrome console

It's interesting to note that both Chrome and node.js operate on the same V8 javascript engine. Here is my take on it: Chrome, despite running internal executions, also handles additional UI tasks which could potentially slow it down On the other ha ...

Calculating the average from a multi-dimensional array requires summing all the elements and

I have a function that calculates the sum of subarrays which have matching keys like this: $totals = array(); $count_loops = 0 ; // First get our totals. foreach ($average as $subKey => $subArray) { foreach ($subArray as $k = ...

"Encountered a Chrome RangeError: The call stack size limit was exceeded while utilizing jQuery's $

As part of my job, I am currently evaluating a web application that involves fetching a substantial amount of data from the server. The data is received as a JSON object using the $.ajax function. It contains numerous sub-objects which I convert into array ...

MongoDB has incorrect date and time records

I've been working on a blog site where entries are logged with the time and date they were posted and stored in MongoDB. Everything was working fine on my local machine, but when I deployed the site to Heroku, I noticed that the date displayed is 8 ho ...

How can we effectively map Typescript Enums using their keys without relying on a Map?

Consider the following Enum instances: export enum TopicCategories { GUIDES = 'Guides', TASKS = 'Tasks', CONCEPTS = 'Concepts', FORMULAS = 'Formulas', BLOGS = 'Blogs' } export enum Top ...