Filter data using the ID in Javascript

My data object contains information about different files, each associated with a courseContentId.

{id: 1864,
 courseContentId: 481,
 fileName: GymMembership.jpg
}
{id: 1865,
 courseContentId: 481,
 fileName: Field.jpg
}
{id: 1866,
 courseContentId: 482,
 fileName: Track.jpg
}

I want to display these files separately based on their courseContentId by creating a new object. Here is my desired output:

{id: 1864,
 courseContentId: 481,
 fileName: GymMembership.jpg
}
{id: 1865,
 courseContentId: 481,
 fileName: Field.jpg
}

{id: 1866,
 courseContentId: 482,
 fileName: Track.jpg
}

Which type of JavaScript function would be best suited for achieving this?

Answer №1

If you want to simplify your code, consider using _.GroupBy function instead of multiple filters.

items = [{id: 1864,
 itemTypeId: 481,
 itemName: 'Item1'
 },
 {id: 1865,
 itemTypeId: 481,
 itemName: 'Item2'
 },
 {id: 1866,
 itemTypeId: 482,
 itemName: 'Item3'
 }]
 
var groupedItems = _.groupBy(items, function(item) {
  return item.itemTypeId;
});
console.log("Grouped Items")
console.log(groupedItems);
console.log("Filter by 481")
console.log(groupedItems["481"]);
console.log("Filter by 482")
console.log(groupedItems["482"]);
<script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js"></script>

Answer №2

const desiredId = 481;
const filteredResult = contentArray.filter(item => item.id === desiredId);

Answer №3

It's a bit tricky to find an easy solution for this problem, but you can give this a shot:

var test = [{
    id: 1864,
    courseContentId: 481,
    fileName: 'GymMembership.jpg'
  },
  {
    id: 1865,
    courseContentId: 481,
    fileName: 'Field.jpg'
  },
  {
    id: 1866,
    courseContentId: 482,
    fileName: 'Track.jpg'
  }
];

console.log(filter(test, 'courseContentId', 481));

function filter(arr, key, value) {
  return arr.reduce((data, item) => {
    if (item[key] == value) data.push(item);
    return data;
  }, []);
}

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

A guide on adding up all the values in a table's columns with JavaScript

I have implemented a web application feature where table rows are dynamically added using JavaScript. Each row contains a Qty Col, Unit Amount Col, and Line Total Col. Users can also remove a line after adding it to the table. In this scenario, I need t ...

The deployment of the Twilio React plugin encountered an issue: Error message stating that the specified resource '/Configuration' could

Currently following this tutorial: I am using a Twilio trial account and attempting to deploy a React plugin. When I run npm run deploy, I encounter the following error message: Error occurred when trying to get Configuration with status code 404, disp ...

Scrolling a div automatically without affecting its parent element

On a page, I have a scrollable list of items that can be updated with a PUT request. Once the update is successful, another network request is made to fetch the updated list. The goal is to automatically highlight the recently updated item in the list. Al ...

Issue with 'backface-visibility' CSS3 property not functioning on any versions of Internet Explorer

I'm looking to implement a specific animation in Internet Explorer. The goal is to rotate an image like a coin, displaying a different image on the other side. I suspect that the issue lies with Backface-visibility in IE, but I'm not entirely sur ...

Utilizing ASCII art in React: A guide to incorporating textual designs into your

I'm having trouble displaying ASCII images correctly on my React app. I've tried various methods, but nothing seems to maintain the form when rendered in the browser. <Grid container id="terminal_banner"> <Grid item ...

Create a new object in Three.js every x seconds and continuously move each object forward in the Z-axis direction

I am currently developing a Three.js endless runner game where the player controls a character dodging cars on a moving road. At this early stage of development, my main challenge is to make the hero character appear to be moving forward while creating the ...

Instructions for modifying the color of the close button in the angularjs ui-select module

I am currently using ui-select for multiple selection in a dropdown. When an item is selected, it displays a cross button on the upper right corner of the selected item. Is there a way to change the color of the cross button to red? <ui-select multip ...

Searching for multiple lines of text within a PHP document

Recently, I have been working on a project that involves an addon making modifications to a crucial system file. As part of this task, I have created a method to locate specific strings within the file: /** * @param $fileName * @param $str ...

Jquery ajax is failing to achieve success, but it is important not to trigger an error

My jQuery ajax request seems to be stuck in limbo - it's not throwing an error, but it also never reaches the success function. This is how my code looks: function delete() { $("input[name='delete[]']:checked").each(function() { ...

Save your AngularJS SVG file as a JPG

I am attempting to develop a custom directive that will allow me to convert an SVG file into a JPG or PNG format. I stumbled upon this website: http://bl.ocks.org/mbostock/6466603 So, I decided to try and implement something similar with the following co ...

Optimize Google Places Autocomplete: Customize the way search results are shown after selection (display only street name and number)

Struggling to update Google's autocomplete input value to only show the selected "streetname number" instead of the full address. It works when the user hits enter, but the value changes back when the input field loses focus. Looking for a simple sol ...

Electron fails to display images in the compiled version

I'm currently troubleshooting an issue related to displaying images using CSS in my electron project. In the latest version of the application, the images are not showing up when linked from a CSS file. However, in a previous version, the images disp ...

A guide to extracting the selected options from a multiple select box and presenting them in a text box

My goal is to have a dropdown menu displaying a list of items, each item corresponding to a specific price. When an item is selected, I want the total price to be automatically calculated and displayed in a textbox. Here is the code for my dropdown menu: ...

Multiple uses of p-fileUpload in primeng are not functioning as expected

Let me explain the situation with this component. I have defined it as follows: <p-fileUpload #fileUpload accept=".csv,.txt" maxFileSize="1000000" customUpload="true" (uploadHandler)="uploadFile($event)"> In my package Json file, I have specified: ...

Is there a way to organize an array of elements into three columns using PHP?

My array of menu items is being displayed on the screen in 3 columns, but I want them to appear differently without altering the HTML structure. Currently, they are listed like this: 1 2 3 4 5 6 7 8 9 I would like them to display as follows: 1 4 7 ...

Looking for a way to choose a button with a specific class name and a distinct "name" attribute using jquery?

I am currently working on developing a comment system. As part of this system, I want to include a toggle replies button when a user posts a reply to a comment. However, I only want this button to be displayed if there are no existing replies to the commen ...

What is the process for serializing an array?

The issue arises when trying to serialize the data returned from the controller function. The objective is to pass this array to the template. views.py: def find_new_authors(request): new_authors = UserProfile.retrieve_new_authors_data() # Us ...

What is the best way to generate an @ symbol using JavaScript?

When coding in Javascript, a challenge I am facing is creating a variable that includes the @ symbol in a string without it being misinterpreted as something else, especially when dealing with URLs. Does anyone have any suggestions on how to handle this ...

Guide to incorporating tesseract OCR into a Cordova/Phonegap application

My attempts to use Tesseract OCR with my app have been unsuccessful despite following the instructions provided here. After inspecting the code using Google Chrome Dev console through the WebView, I encountered an error: Uncaught SyntaxError: Unexpected ...

AngularJS routing with html5mode causing 404 error when using htaccess

I am currently working on my very first angularjs application using version 1.6x, and I am encountering some 404 errors with my router. Here is how my router is set up: app.config(function($routeProvider, $locationProvider) { $locationProvider.html5M ...