Using Ramda to retrieve objects from an array by comparing them with each element in a separate array

I have two arrays:

ids = [1,3,5];

The second array is:

items: [
{id: 1, name: 'a'}, 
{id: 2, name: 'b'}, 
{id: 3, name: 'c'}, 
{id: 4, name: 'd'}, 
{id: 5, name: 'e'}, 
{id: 6, name: 'f'}
];

I want to create a new array with only the items whose IDs match the ones in the 'ids' array:

array = [{id: 1, name: 'a'}, {id: 3, name: 'c'}, {id: 5, name: 'e'}];

I am struggling to figure this out. I have tried:

console.log(R.filter(R.propEq('id', <don't know what should be here>), items);
console.log( R.pick(ids)(items))

Answer №1

If you are interested in using Ramda, here is an example:

const ids = [1,3,5];

const items = [
{id: 1, name: 'a'}, 
{id: 2, name: 'b'}, 
{id: 3, name: 'c'}, 
{id: 4, name: 'd'}, 
{id: 5, name: 'e'}, 
{id: 6, name: 'f'}
];

console.log(

  R.filter(R.compose(R.flip(R.contains)(ids), R.prop('id')), items)

);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

Answer №2

To filter items based on specific ids, you can utilize the .filter and .indexOf methods from ECMAScript 5. Please note that these methods are not compatible with IE8.

var ids = [1, 3, 5];
var items = [
  {id: 1, name: 'a'}, 
  {id: 2, name: 'b'}, 
  {id: 3, name: 'c'}, 
  {id: 4, name: 'd'}, 
  {id: 5, name: 'e'}, 
  {id: 6, name: 'f'}
];

var filteredItems = items.filter(function(obj) {
  return ids.indexOf(obj.id) > -1;
});
console.log(filteredItems); // Outputs: [{id: 1, name: 'a'}, {id: 3, name: 'c'}, {id: 5, name: 'e'}];

Answer №3

Perhaps a more concise solution without using Ramda

items.filter(x=>ids.includes(x.id))

Answer №4

One effective approach is to utilize a hash table for expedited data retrieval.

var ids = [1, 3, 5],
    items = [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'} ],
    filtered = items.filter(function(obj) {
        return this[obj.id];
    }, ids.reduce(function (r, a) {
        r[a] = true;
        return r;
    }, Object.create(null)));

document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');

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

send parameter when clicking a link rather than using a hashtag

One interesting feature on my website is a menu link with the attribute title=.roc. When this link is clicked, I want to extract this attribute and click on an element with the same attribute on the destination page. Let's consider a scenario where I ...

Despite the value being true, the if statement does not work when used with a Mongoose object in Node.js

Currently working on a bidding app, Below is the schema for the bidding model const bidSchema = new mongoose.Schema({ name: String, price : Number, description: String, location: String, specilization: String, image: String, ...

execute ajax within a standalone javascript function

I am just starting to learn about jquery and ajax, and I have a specific requirement to call ajax from a separate javascript function. The issue is that the JSP file is dynamically generated and the button IDs in the JSP file are also created using a for l ...

What is the significance of the "@" in JXON conversion in JavaScript?

Looking at an XML structure like the one below: <calendar> <month year="2013" num="5"> <day num="1"> </month> </calendar> I decided to convert it to JSON using MDN's JXON Snippet 3. https://developer.moz ...

Organize the dataset into groups based on every possible key

Hi there, I'm facing a challenge while developing an application using NestJS/Prisma. The task at hand is to extract unique results from a table in order to display them in a filter on the front-end. Let me give you an overview of my table structure ...

"message": "Please provide a valid user path.",

When attempting to store the user in the database, the response indicates that the "user" path is required even though the user value is present in req.body and logged for verification purposes. However, the issue persists with storing it in the database. ...

Tips for improving modularity in my frontend JavaScript code?

I'm currently developing a unique Node.js / Express application that visually represents text notes as a network to offer users a clear summary of the connections between different notes. The project heavily relies on frontend functionalities, requir ...

"Implementing a method to update an object by its Id within a nested array that includes children, and then managing the state in

How can I dynamically toggle the isExpanded property on click based on an element's ID in a React project? Below is the JSON data structure I am working with const handleExpandOutlineItem = (id: string) => {} This is the structure of my JSON data: ...

Using a JSON array in PHP script

I'm trying to incorporate a JSON array within my PHP code, specifically within a for loop where I need to split the array into two parts and then merge them back together. Unfortunately, my current approach has not been successful. The purpose of this ...

Issue encountered when attempting to alter the action attribute of a form: receiving an error message stating 'undefined is not a function'

I am attempting to dynamically set the action attribute of a form based on the button clicked in order to navigate away from a page. Once the action is updated, the form should be submitted and the new action carried out. Below is my jQuery function: fun ...

Securing RESTful APIs with stringent security measures

Lately, I've been delving into using modern front end technologies such as React and Angular. This has led me to explore tools like JSON Server for simulating restful database interactions. I've noticed that most REST APIs require authentication ...

The JavaScript program for the shopping list is experiencing issues with the formatting of list items

I have been working on developing a shopping list program using JavaScript. The program includes an input box and an "add item" button, which adds the text entered in the input field to an unordered list as a list item. Each list item also contains an imag ...

How to delete a line from a file in Node.js without modifying the buffer variable

Hello everyone, I am just starting to explore the world of Nodejs Recently, I created a function that reads data from a file, saves it in an array variable, and then makes some changes to this variable before writing it back to the file. The code snippet ...

Error: Invalid Request - Nodejs Request Method

As part of my project involving payment gateway integration, I needed to make a call to the orders api. However, I encountered an error message: {"error":{"code":"BAD_REQUEST_ERROR","description":"Please provide your api key for authentication purposes."} ...

Difficulty in accurately retrieving the value in a PHP echo statement using jQuery

$id = "123"; When on the page book.php, $id is passed to an external jquery-book.php file. <script type="text/javascript"> var id = '<?php echo $id; ?>'; </script> <script type="text/javascript" src="jquery-book.php"& ...

Tips for avoiding accidental double mouse clicks occurring simultaneously

$(document).ready(function() { $(".voteMe").one('click', function (event) { event.preventDefault(); //my customization $(this).prop('disabled', true); }); }); the provided code enabl ...

execute the function within the data() method

I'm currently working on retrieving data for my search tree, and I'm facing issues with fetching the data directly from axios or calling a function because it cannot be found. export default { name: 'SideNavMenu', data () { return ...

Tips for updating a section of a webpage without the need to redirect to a different page: use technologies such as Express, Nodejs, and M

In the midst of developing a two-player game where one player must guess a word within 10 tries, I find myself facing a challenge. I need to display the player's guesses and scores in a table without refreshing the entire page. Unfortunately, my exper ...

Combining Import and Require in a Node JS File

Having some trouble with the normalize-url package. It needs to be imported instead of required since it's not supported in ES module. I tried to work around this by adding some code I found online, but it doesn't seem to be fixing the issue for ...

The sequence of indices in a for loop and making Ajax requests

I'm dealing with a challenge related to executing ajax requests within a for loop. Despite researching solutions online and implementing them to prevent synchronous request execution, I still face an issue in maintaining the correct order of the succe ...