Using JavaScript, sift through various elements in a large array and extract only specific

I have retrieved an array containing 2400 objects from our server, totaling about 7MB in size, and I need to extract specific values from it. Currently, I am using a combination of the filter and slice methods:

 const keyword = 'whatever word';
 const recommendList = bigArray.filter(item => item.name.includes(keyword)).slice(0, 5);

I understand that the filter method iterates through all elements in the array which may impact the performance of my app (React Native) due to the large data set. Is there an alternative approach to filter the array for certain values without iterating through all elements?

Answer №1

If you want to break the loop when you reach the 5th element, you can follow this approach:

const keyword = 'v';
const bigArray = ['a','v','a','v','a','v','a','v','a','v','a','v','a','v','a','v','a','v'];
const recommendList = [];
for (let i=0; i<bigArray.length; i++) {
  if (recommendList.length == 5) { 
    break; 
  }
  
  if (bigArray[i].includes(keyword)) {
    recommendList.push(bigArray[i]);
  }
}
console.log(recommendList);

If you prefer not to use lambda operations, you can utilize methods like some or find which will stop iterating after finding the first true response.

const bigArray = [{
    "name": "a"
  },
  {
    "name": "v"
  },
  {
    "name": "a"
  },
  // more objects...
];

const keyword = 'v';
const recommendList = [];

bigArray.some(obj => {
  if (obj.name.includes(keyword)) {
    recommendList.push(obj)
  }
  return recommendList.length === 5;
})

console.log(recommendList);

Answer №2

let term = 'specific term';
let suggestions = [];
for (let j=0; j < largeData.length; j++) {
  if (suggestions.length >= 5) 
    break;

  const element = largeData[j];
  if (element.title.includes(term)) 
    suggestions.push(element);
}

Answer №3

To enhance efficiency, consider processing the array as a seamless sequence.

Check out this example built on the iter-ops library:

import {pipe, filter, take} from 'iter-ops';

const result = pipe(
    largeArray,
    filter(item => item.name.includes(keyword)),
    take(5)
);

console.log('matches:', [...result]);

This method avoids unnecessary iterations and stops once the first 5 matches are found.

Answer №4

When considering this scenario, my belief is that using a filter operation (with the complexity being O(n)) would be the optimal solution to minimize any performance impact.

For example, if you were to filter out only 1500 values from a total of 2400 objects, then you would be left with a result set containing just 1500 objects, while the remaining 900 objects would go unused. In such cases, it becomes essential to iterate through the collection at least once.

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

Customizing the toString method within an object's definition

There was a question asked previously regarding the overriding of toString. Here is the answer provided: function Foo() {} Foo.prototype.toString = function() { return "this is Foo"; } However, my question is: Is it possible to include this prototy ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

What is causing the loss of context for 'this' in the latest Angular 1.5 components?

Encountering a strange issue with the new components. Previously, in version 1.4 directive, we had this block of code... (function () { 'use strict'; angular.module('app.board').directive('dcCb', dcClipboardCopy); funct ...

Send the form to the webpage and display various div elements based on the entered information

I have created a form that is designed to display one of four hidden divs on a page, depending on the input provided. Here is the form: <form> <input id="place" name="place" type="text"> <input name="datepicker" type="text" id="datepicker" ...

Different methods for conserving memory while comparing arrays instead of using np.newaxis()

Considering every vector from one array and comparing it to all vectors from another array, counting the number of matching symbols per vector is what I am aiming for. An illustrative example will help clarify this concept. I have two arrays, a and b. For ...

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...

Merging elements in an array according to specific rules and documenting the results

Given an array of numbers in 1D, the task is to iterate over the array by adding consecutive elements to form sums. When the sum reaches a certain value, it becomes the first element of a new array. This process is then repeated to cover the entire array. ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

Making an AJAX request to a different domain

My understanding is that the AJAX cross-domain policy prevents me from simply making a call to "http://www.google.com" using an AJAX HTTP request and then displaying the results on my website. I attempted to use the dataType "jsonp", which theoretically s ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...

Loading suggestions ahead of time in Vuetify's autocomplete feature

I recently started learning the Vuetify framework and have been successfully using most of its components. However, I am facing an issue with the autocomplete component. When I try to set a value during creation, it does not work as expected. I attempted t ...

What is the best class to implement in my jQuery code?

Currently in the process of developing a customized Google Chrome extension. Encountering an issue or experiencing confusion regarding the selection of a specific class to integrate into my jQuery script, particularly with numerous classes associated with ...

Guide on filling out multiple forms with just one form

I am currently working on creating an online application where users can fill out the contact forms on my two other websites, located at and , using the form on my third website at . Essentially, when a user submits the form on , it should automatically ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

Guide on reading input from the standard input and storing it into a two-dimensional Python array containing only integers

How can I read a 2D array of integers in Python from either stdin or a file? Here is an example of code that does not work: from io import StringIO from array import array # simulate stdin stdin = StringIO("""1 2 3 4 5 6""") a = array('i') a. ...

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

The window.open() function in Microsoft Edge is failing to respect specified width and height parameters, causing it to

The functionality of the window.open method in the latest Edge browser on Windows 10 preview Build 10130 doesn't seem to align with the expected behavior outlined in the specification. If you try out the sample code provided at https://msdn.microsoft ...

Unveiling Fresh URLs within an iFrame

Here is the current situation: www.mywebsite.com/Pagex.html - On this page, there is an iFrame with a default URL (src) from a different domain than the host page (Pagex.html). The code inside the iFrame is a user input form with a submit button. Upon su ...

Repurposing components like custom text inputs, spans, and more in ASP.NET MVC using Razor

Our team is currently working on a website project where we keep re-using components repeatedly. One particular instance involves a span that functions as a warning light. It's accompanied by some C# code with properties for color and text, Javascript ...

Filtering Objects in Javascript: A Step-by-Step Guide

Consider an array containing various object details: Array [ Object { "deleted": null, "disabled": null, "id": "456", "price": 970, "size": Object { "br": 35, ...