Retrieving the initial element from an array when a certain parameter is left blank

Looking at the following array:

const data = [
  {id: 1, courses: [{title:"course1.1", results:[]}, {title:"course1.2", results:[]}]},
  {id: 2, courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]},   
];

I am attempting to retrieve the first item in the data array that has a course with no results.

I attempted the following approach:

data.filter(session => session.courses.filter(course => course.results.length <= 0));

However, it is returning all items for some unknown reason.

Any assistance on this matter would be greatly appreciated, thank you!

P.S. I have already tried using Array.some and a simple forEach without success.

Edit: I forgot to mention that I conducted a test on jsfiddle, https://jsfiddle.net/jonathanlaf/4os0fzv1/

Edit2: I understand that filter will return all matching results, but I just need to take the first index of the newly returned array.

Edit3: I actually expect the newly returned array to look like this:

const updatedData = [
  {id: 2, courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]},   
];

Answer №1

Here's the solution you're looking for:

const data = [ {id: 1,courses: [{title:"course1.1", results:[{title:"result1.1.1"}, {title:"result1.1.2"}]}, {title:"course1.2", results:[]}]}, {id: 2,courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]}, {id: 3,courses: []}];

console.log(data.reduce((accumulator,current) => (current.courses.length ? accumulator.push({ id: current.id, courses: [...current.courses.filter(({results}) => !results.length)]}) : true) && accumulator, []))

This code snippet utilizes reduce and filter methods to achieve the desired outcome.

Update: The code now handles scenarios where the courses array is empty without any results, such as {id: 3,courses: []}.

Answer №2

A new approach is available to create mappings for objects without changing the original dataset.

var array = [{ id: 1, courses: [{ title: "course1.1", results: [{ title: "result1.1.1" }, { title: "result1.1.2" }] }, { title: "course1.2", results: [] }] }, { id: 2, courses: [{ title: "course1.1", results: [] }, { title: "course1.2", results: [] }] }],     
    result = array.map(o => 
        Object.assign(
            {},
            o,
            { courses: o.courses.filter(({ results: { length } }) => !length) }
        )
    );
    
console.log(result);

Answer №3

    const data = [
    {id: 1,courses: [{title:"course1.1", results:[{title:"result1.1.1"}, {title:"result1.1.2"}]}, {title:"course1.2", results:[]}]},
    {id: 2,courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]},   
    ];    
    let availableResults = data.find(item => -1 < item.courses.findIndex(subItem => subItem.results.length <=0))
    console.log(availableResults)

Find information in an Array Find the Index of an Element in an Array

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

The functionality of the Jquery table sorter appears to be malfunctioning, causing it to not

Recently, I included Jquery table sorter in the header of my webpage. However, as soon as I implement the following code in my javascript: $("table").tablesorter(); All my other Jquery functionalities stop working and unfortunately, the table sorter do ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

Determining the Maximum Number of Characters Allowed in a Div Using jQuery

Could anyone provide guidance on how to populate a div with single characters? I want the div to span the width of the viewport. The code to get the width is: $(window).width(); I would like JavaScript to generate HTML similar to this: <div id="text ...

Conceal an element using a transition effect, initiating its positioning at the center instead of the default

One of the challenges I'm facing is with a video element that I want to hide gradually when clicking on another element. The issue is that after the animation completes, the video ends up hidden at the top-left corner of the screen instead of at the c ...

What is the reason for updating only one out of three charts using react-chartjs-2?

Recently, I came across an issue with a modal that includes a text field for recording numerical values. These recorded values are then passed through a loop to populate an array based on the input. Subsequently, these values get updated in 3 different gra ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

javascript: Retrieve specific row data from Bootstrap Modal table and pass it back to the main webpage

I am a beginner in using bootstrap modals and JavaScript, and I need assistance in resolving the following issue. Desired Outcome: 1. When the parent screen opens the modal window, it should display a form to find a username: <div class="form-gro ...

Using jQuery UI Tabs to Dynamically Select a Tab Based on a Link

Recently, I have been exploring the idea of using a script to open a specific tab: $('.tofour').click(function() { // bind click event to link $tabs.tabs('select', 3); // switch to third tab return false; }); However, my dilem ...

Ways to retrieve the bounding rectangle of an element PRIOR to applying a transformation?

Is there a way to obtain the dimensions and position of an element using Element.getBoundingClientRect(), but without taking into consideration any transformations applied through the CSS property transform? I am looking for a method that provides the rect ...

Accessing JavaScript results in PHP

Hello everyone! I am working on creating a dropdown menu for selecting time using JavaScript to get the computer's current time. My goal is to have an output that automatically selects the option in the dropdown if it matches the computer's time. ...

Unable to choose daylight saving time using the AnyTime datepicker

Looking for a solution like the AnyTime datepicker? Check out this link: I am facing issues with selecting specific times in certain timezones, such as being unable to select 2015 29 march 02:00 while in the CET timezone. Despite these challenges, I woul ...

Is the mounted hook not being triggered in a Nuxt component when deploying in production (full static mode)?

I have a component that is embedded within a page in my Nuxt project. This particular component contains the following lifecycle hooks: <script> export default { name: 'MyComponent', created() { alert('hello there!') }, ...

During the deployment of a ReactJS app, webpack encounters difficulty resolving folders

While developing my ReactJS app, everything ran smoothly on localhost. However, I encountered some serious issues when I tried to deploy the app to a hosting service. In my project, I have a ./reducers folder which houses all of my reducers. Here is the s ...

Storing Byte Array in a File using JavaScript

I am working on a Java REST webservice that returns documents as byte array. I am trying to write JavaScript code that will retrieve the response from the webservice and save it to a file for downloading as a PDF. However, when testing my sample code, the ...

What are the key differences between glTFLoader and ObjLoader in threejs?

Throughout my experience with three.js, I have always relied on .obj files to import models. However, I recently came across information suggesting that the shift towards using .gltf files is now preferred. Upon trying to work with .gltf files, I've ...

Issues with Angular functionality

I'm a newcomer to Angular and I am trying to recreate this example from jsfiddle in order to experiment with nodes. However, I am encountering issues with the Angular setup. Firstly, the jsfiddle is causing confusion because the application names do n ...

Please restrict all scores to only one decimal point and ensure that all integer scores include a ".0" at the end, except for scores of 10 or 0

Ensure scores are rounded to a single decimal point and update all integer values with .0, except for 10 and 0. For example: 0.972 should be 0.9 2.83 should be 2.8 All integer scores will be updated as: 0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 I have ...

What is the simplest method for preserving the Redux state?

What is the most efficient method to maintain state in Redux even after a website refresh? I would prefer not to rely on redux-persist if there are alternative options available. ...

To prevent the page focus from shifting, make sure to force click on a blank link

My question involves an empty link: <a href="#" id="stop-point-btn">+ add stop-point</a> This link is connected to a JavaScript function: $("#stop-point-btn").bind("click", addStopPoint); The JS function simply inserts content into a specif ...

Add a selection of paths from a different package into the Router

Seeking a quick solution here. I have the following code snippet and I am looking to efficiently import a multitude of routes from my package. These routes should be managed by the package I am constructing. If I introduce a new page in the package (e.g., ...