Ways to remove elements from array of objects that match items in separate array of strings using javascript

In my JavaScript code, I am looking to filter an array of objects based on an array of strings.

Here is the input array of objects:

const input = [
    {
        id: 1,
        name: 'first',
        type: 'first_type',
    },
    {
        id: 2,
        name: 'second',
        type: 'second_type',
    },
    {
        id: 3,
        name: 'third',
        type: 'third_type',
    },
]; 


const chosen_items = ['1','2']

The goal is to filter the items in the input array whose id matches with the ids in the chosen_items array. The expected output should be as follows:

const output = [
    {
        id: 1,
        name: 'first',
        type: 'first_type',
    },
    {
        id: 2,
        name: 'second',
        type: 'second_type',
    },
]

I attempted a solution using React's useMemo hook, but it did not give the correct output. It seems to be filtering based on index rather than id.

const output = React.useMemo(
  () => chosen_items.map(id => input[id]).filter(negate(isNil)),
  [input, chosen_items]
);

As a result, the output I got was different from what I expected:

output = [
    {
         id: 2,
         name: 'second',
         type: 'second_type',
     },
     {
         id: 3,
         name: 'third',
         type: 'third_type',
     },
 ]

If anyone can help me fix this issue and correctly filter the input array by id, I would greatly appreciate it. Thank you!

Answer №1

To achieve this, you can utilize the filter() method. It is important to note that in the input array, the id is a number, whereas in the chosen_items array, the id is represented as a character.

const input = [
    {
        id: 1,
        name: 'first',
        type: 'first_type',
    },
    {
        id: 2,
        name: 'second',
        type: 'second_type',
    },
    {
        id: 3,
        name: 'third',
        type: 'third_type',
    },
]; 


const chosen_items = ['1','2']

let result = input.filter(a => chosen_items.includes(a.id + ''))
console.log(result)

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

Update image attributes (such as src, alt, etc.) after a successful AJAX request (and also help me troubleshoot my AJAX

The image link I am currently using is: echo "<br/><div class='right' id='post" . $id . "'> <img id='thumb' src='/images/like.png' title='Like it?' alt='Like button' onC ...

The file extension validation function is not functioning correctly on Windows, however it is successfully working as expected

async upload( @UploadedFile() file: Express.Multer.File, @Body() body: FileUploadDto, ) { const forbiddenExt = [ '.exe', '.bat', ]; const fileName = file.filename || f ...

What steps can I take to modify the class of a button once it has been clicked using JQuery?

Currently, I am experimenting with Jquery to dynamically change the classes of bootstrap buttons when they are clicked. However, I have encountered a limitation while using toggleClass. The issue is that I am only able to toggle between two classes, whic ...

Typescript version 2 is facing difficulties in resolving an external node module

Lately, I've been experimenting with prototyping using koa and Typescript 2.0. In my simple project, I've configured the tsconfig.json file like this: { "compilerOptions": { "outDir": "./bin/", "sourceMap": true, "no ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...

Step-by-step guide: Uploading files with Ajax in Codeigniter

I am facing an issue with updating data and uploading an image when editing a row in my grid. Although the data is successfully updated, I am encountering difficulties in saving the image file to a folder. Here is what I have tried: While using AJAX, I ...

Develop a radio button filter utilizing the "Date of Creation" attribute, implemented with either jquery or JavaScript

I am currently utilizing a customized Content Query Web Part to load a series of list items. Each of these items has an XSLT attribute known as the Created Date. Shown below is an example of the markup: <div class="item" createddate="2014-01-22 13:02 ...

Tips for creating a scrollable smiley input field

I have a chat system where I am incorporating smileys from a predefined list. QUERY I am looking to create a scrolling feature for the smileys similar to how it is implemented on this particular website. The twist I want to add is to have this functiona ...

Encountering a blank screen on the Swagger route in ExpressJs: How to troubleshoot

I have set up swagger-ui-express with swagger-jsdoc in my Express.js project following various tutorials and official documentation. However, despite implementing everything correctly, I am facing an issue where the Swagger URL displays a blank white scree ...

Remember a MySQL query using JavaScript

For quite some time, I've been on a quest to unveil the solution to this issue that seems relatively straightforward, yet continues to elude me. The crux of the matter is my desire to "recall" a functional mysql query. With an HTML button and a span ...

Running Javascript code after rendering a HandleBars template in Node/Express

I have a Node.js application where I am trying to load data into a jQuery datatable after the data has been fetched. Currently, I am able to populate the table with the data, but I am facing issues initializing the datatable. Here is how I render the temp ...

Locate the closest pals near my present whereabouts

Is it possible to find my friends by obtaining their location from their mobile phones when they are near me? I have a code snippet below with the variable cities where I can input the numbers of my friends. Can I achieve this or do I need to make some m ...

Ways to categorize by a particular date

const vehicleDetails = [ { "record_id": "2ff8212f-5ec9-4453-b1f3-91840a3fb152", "status_date_activity": { "On Rent": 1662021991000 } }, { "record_id": "c8c1 ...

How to retrieve information from an Angular 2 subscribe method

Here is my Objective. @Component({ selector: "data", template: "<h1>{{ fetchData() }}</h1>" }) export class DataComponent{ this.http.get(path).subscribe({ res => return res; }) } In the scenario where fetchData was in ...

Exploring the dynamic world through HTML5 canvas and animated objects

Today I am exploring HTML 5 canvas and experimenting with moving 3 circles on the canvas. Based on my research, it looks like I need to continuously redraw the circles (perhaps every 60 milliseconds) and clear out the old circle before rendering the new on ...

Ruby on Rails allows for the selection of values in a dropdown menu to trigger the visibility of different sections of HTML

As a newcomer to Rails, I was able to successfully implement the onclick function for a f.checkbox element. Now, my challenge lies in achieving a similar functionality for a f.select element within a _form. Below is the code snippet that works for a chec ...

Ways to verify the user's authentication status on the server end

Before displaying an HTML page, I need to verify user authentication. Here is a snippet from my server.js: const express = require('express'); var jquery = require('jquery'); var admin = require("firebase"); const app = expre ...

What is the best way to design functions that can return a combination of explicit types and implicit types?

When looking at the code provided below, function system(): ISavable & ISerializable { return { num: 1, // error! save() {}, load() {}, serialize() {}, deserialize() {}, } } interface ISavable { sa ...

Update the CSS styling of a parent div based on the active state of specific child divs

I have a class with 4 distinct columns. div class="mainContent"> <div class="left-Col-1" *ngIf="data-1"> </div> <div class="left-Col-2" *ngIf="!data-1"> ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. https://i.ss ...