How to Retrieve Objects Based on IDs in JavaScript

My current setup involves a collection of objects structured like this:

const items = [
     {
          name: 'book',
          id: 3
     },
     {
          name: 'pen',
          id: 1
     },
     {
          name: 'paper',
          id: 5
     }
];

I also have an array of Ids:

const ids = [1, 5];

What I want to achieve is to extract all the "items" that match any of the ids in my list, resulting in this:

const result = [
     {
          name: 'pen',
          id: 1
     },
     {
          name: 'paper',
          id: 5
     }
]

I currently use a method where I iterate through each id and check for matches in the items:

let result = [];
for (let i = 0; i < ids.length; i += 1) {
     const foundItem = items.find(x => x.id === ids[i]);
     result.push(foundItem);
}

However, considering that my actual dataset can be quite large with thousands of entries and the list of ids could also be extensive, I'm curious if this approach is the most efficient one or if there's a better way to accomplish the same goal.

Is there a more optimized way to map these results?

Answer №1

To gather all the different types of fruits, you can organize them based on their unique id and then create a map of these collected ids.

const
    fruits = [{ name: 'pear', id: 4 }, { name: 'grape', id: 6 }, { name: 'kiwi', id: 9 }],
    ids = [4, 9],
    fruitsById = {};

for (const fruit of fruits) fruitsById[fruit.id] = fruit;

const finalResult = ids.map(id => fruitsById[id]);

console.log(finalResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If each object's id is guaranteed to be unique, the solution below will provide more efficiency in terms of lookup.

I have restructured the array of objects into an object where the keys are the id properties for faster access.

const animals = [
     {
          type: 'lion',
          id: 5
     },
     {
          type: 'elephant',
          id: 2
     },
     {
          type: 'tiger',
          id: 7
     }
];

var animalsObj = {};

animals.forEach(function (a) {
  animalsObj[a.id] = a.type;
});

const animalIds = [2, 5];

var output = [];

animalIds.forEach(function (y){
  if (animalsObj[y]) {
    output.push({type: animalsObj[y], id: y});
  }
});

console.log(output);

Answer №3

If you want to optimize the process, one way is to "hash" the ids and then filter them through a lookup function. Here's an example:

const items = [
     {
          name: 'desk',
          id: 4
     },
     {
          name: 'chair',
          id: 7
     },
     {
          name: 'lamp',
          id: 9
     }
];

const keys = [7, 4];

const filteredItems = items.filter(function (element) {
// return this.remove(element.id); // or use this return for distinct ids
  return this.contains(element.id);
}, new Set(keys));

console.log(filteredItems);

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

Bash - Finding the final position in an array

Is there a way in Bash to retrieve the last index of an array efficiently? Although the method $((${#array[@]} - 1)) gets the job done, it's not the most elegant solution. In order to access the last element of an array, one can simply use ${myarra ...

Angular: facing difficulty displaying static html pages on server, although they render correctly when run locally

Within my Angular project, I have stored a few static html files (specifically sampleText.html) in the src/assets/html folder. In one of my components, I am attempting to fetch and display this file. The following code is being used for this purpose. Every ...

Mongoose Express: Limiting increments to a maximum of 5

Currently, the essential functionality implemented is 1 click = 1 vote. The system successfully updates a vote parameter in MongoDB and increments it as expected. However, after approximately 5 votes, the incrementing process halts. Upon refreshing the bro ...

How can I make sure that my function returns a mutated object that is an instance of the same class in

export const FilterUndefined = <T extends object>(obj: T): T => { return Object.entries(obj).reduce((acc, [key, value]) => { return value ? { ...acc, [key]: value } : acc; }, {}) as T; }; During a database migration process, I encounte ...

What is the best way to retrieve the index path of a tableview cell filled with data from an array?

I am working with a table view cell that contains 5 different sub-cells. Each sub-cell has a label with one of the following elements: a text field, text, view, switch, or slider. My goal is to identify the specific table view cell at a certain index path ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

troubles with variables in AngularJS Formly templates

Having trouble displaying model or other variables in my template? Check out this link for reference: http://jsbin.com/wofulinufo/edit?html,js,output. Question: What is the solution for displaying variables from controller? Even when I try using {{model} ...

Does LABJS include a feature for executing a callback function in the event of a timeout during loading?

When using LabJS to asynchronously load scripts with a chain of dependencies, if one of the scripts breaks (due to download failure or connection timeout), it seems that the remaining scripts in the chain will not be executed. Is there a way to define a ...

Updating fields in MongoDB using dot notation

In my Mongo Schema, I have defined the following structure: var OrderSchema = new Schema({ postcode: String, ... status: { last_check: { type: Date }, date: Date, code: String, postnum: String, text: Str ...

How to Convert an Array of Integers to a Single Integer in Swift

While working with Swift 3, I managed to create an Int array from numbers and then reversed it. var rev:String = String(number) var pro:String = String(rev.characters.reversed()) var myArr = rev.characters.flatMap{Int(String($0))} myArr = myArr.sorted { ...

Locate all entries with inclusive connections within a complex many-to-(many-to-many) relationship using sequelizejs

There is another related question in the Software Engineering SE. Let's think about entities like Company, Product, and Person. In this database, there exists a many-to-many relationship between Company and Product through a junction table called Co ...

Guide to setting up a click event for a group of input items, specifically radio buttons

I am looking to trigger some JavaScript code whenever a user clicks on any of the radio buttons in my web application. Despite my efforts, I am having trouble capturing a click event on the list of input elements. Currently, in my app, I have included the ...

Changing a JSON string array into an NSArray in Swift

When I receive a response, it looks something like this in some key: "abc" : "[{\"ischeck\":true,\"type\":\"Some type\"},{\"ischeck\":false,\"type\":\"other type\"}]"]" To convert this into a no ...

JavaScript regex problem

As I am handling a specific string: £1,134.00 (£1,360.80 inc VAT) I am currently attempting to isolate the numerical values as follows: ['1,134.00','1,360.80'] My approach involves utilizing this regex pattern in Javascript: /&bs ...

What is the best way to get jsDoc "import" to function properly in vscode?

Is it possible to import a node module using @import in Visual Studio Code? I'm trying it but it doesn't seem to be recognized. Am I missing something? https://i.stack.imgur.com/zq1rz.png ...

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...

Getting the value of a hidden input field within a div by accessing the event.target that initiated the event in JavaScript

I am working with a set of li elements, each containing specific child elements structured like this: <li class="list"> <!--Parent--> <input type="hidden" id="id" value="3"> <!--Child 1--> <div class="cd-1">....</div ...

How can I assign a prop to a component within the root layout in Next.js version 13, especially when the root layout is required to be a server-side component at all times?

I need assistance with a project I'm working on. My goal is to create a SongPlayer component in Next.js version 13 that plays music and is positioned at the bottom of the window, similar to Spotify's player. However, my SongPlayer component requi ...

Guide on assigning a material to ColladaLoader or OBJLoader

I've searched extensively through the documentation and numerous examples, but I couldn't find the correct syntax for assigning a material to either a Collada .dae or OBJLoader .obj file. Json files seem to work well when creating a Mesh, with t ...

Swapping out ChildNode data for HTML elements

When attempting to replace a node value with HTML content, I encountered an issue where the HTML tags were being displayed on the HTML page instead of applying the intended style. <style> .YellowSelection { background: yellow; } < ...