Transfer the values of specific keys in an array to a separate array based on the values of another key within the same object that satisfy a particular condition

I am seeking a refined solution to create a function that retrieves the names of legal drivers from a given array of people:

function getNamesOfLegalDrivers(people) {



}

const driverArray = [
{ name: 'John', age: 14 },
{ name: 'Joey', age: 16 },
{ name: 'Jane', age: 18 }
];

console.log(getNamesOfLegalDrivers(driverArray), '<-- should output names of individuals over 16 years old, like ["Joey", "Jane"]');

Answer №1

If you're searching for methods on the Array prototype, consider using filter and map.

JavaScript

function listNamesOfEligibleDrivers(people) {
  return people
    .filter(function(person) { return person.age >= 16; })
    .map(function(person) { return person.name; });
}

Explanation from MDN

  • Array.prototype.filter The filter() method creates a new array with elements that meet the criteria specified by the given function.
  • Array.prototype.map The map() method generates a new array by applying a function to each element of the original array.

Answer №2

function retrieveLegalDriverNames(people) {
  return people
    .filter(person=>person.age >= 16) //obtain an array of person objects aged 16 and older
    .map(person=>person.name) //extract names of individuals in the filtered array

}

Answer №3

One way to achieve this is by implementing the following function:

function retrieveLegalDriverNames(personnel) 
{
    var legalDriverNames = [];

    for (var index in personnel) {
        if(personnel[index].age >= 16){
           legalDriverNames.push(personnel[index].name);
        }
    }

    return legalDriverNames;
}

const samplePersonnelArray = [
{ name: 'John', age: 14 },
{ name: 'Joey', age: 16 },
{ name: 'Jane', age: 18 }
];

console.log(retrieveLegalDriverNames(samplePersonnelArray));

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

What is the best way to navigate through an HTML node tree, including all of its sub elements, when walking through

Do you know of a way to iterate through the entire hierarchy of HTML elements and check each one for attributes and more without using JavaScript? We currently have a JavaScript solution that iterates through each child element and all their descendants. ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

Exploring the capabilities of the Scripting.FileSystemObject within the Microsoft Edge browser

With the removal of ActiveXObject in Microsoft Edge, what is the alternative method to use FileSystemObject in this browser? I am currently working on developing a Microsoft Edge plugin that captures the HTML code of a web page and saves it as a .txt fil ...

Automatically launch a popup window specified in JavaScript

Aim:- I am trying to automatically open a radwindow from the server-side based on a specific IF condition. Snippet Used:- In the aspx page, I have defined the radwindow as follows: <telerik:RadWindowManager Skin="WBDA" ID="AssetPreviewManager" Modal= ...

Converting an HTML form with empty values into JSON using JavaScript and formatting it

While searching for an answer to my question, I noticed that similar questions have been asked before but none provided the solution I need. My situation involves a basic form with a submit button. <form id="myForm" class="vertically-centered"> ...

What is the best way to establish my permit requirements on a monthly basis?

An employee is only allowed to request up to 3 permits per month. If they need a fourth permit, they will have to wait until the following month. Here is my table structure for permissions: Permissions id (integer), format (text), date_r ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

Maximizing the potential of NPM modules by harnessing the power of the package.json file

Currently, I am working on developing an NPM module for a command-line tool. Upon installation of the package, it is essential to access and read the user's package.json file. While I understand how to read the file syntactically, my main concern lies ...

Newbie problem with MVC Razor: struggling to upload file via Ajax

I am experiencing an issue with my AJAX file upload using C#-Razor. For some reason, when I click the button to submit the file, the controller method is not being triggered. Can anyone provide a solution to this problem? Here is the code snippet: View ...

What is the best way to pass a file and a string to my C# backend using JQuery Ajax?

I have a user interface with two input fields - one for uploading a file and another for entering the file's name. I need to capture both the file (as binary data) and its corresponding name in a single AJAX request, so that I can upload the file usi ...

Navigating through and extracting data from an object in JavaScript

Given the function call destroyer([1, 2, 3, 1, 2, 3], 2, 3);, I am trying to retrieve the last 2, 3 part after the initial array. However, I am unsure about how to achieve this. When I use return arr[6]; or return arr[1][0], both statements do not return ...

How to efficiently handle events for an entire array in Java using a single EventHandler

I've been searching all over the internet for a solution to my problem, but I still can't figure it out after spending several hours. In my program, I have an array of 40 imageViews displayed on the screen. What I want is for the image in the sel ...

Utilizing document.write() for displaying markup content

I have an inline SVG stored as a variable on my webpage and I am making some changes to it. How can I display viewText on the page (not the SVG image) with the modifications? What is the best way to make viewText appear on the page? For instance: ...

Dealing with child elements in isomorphic React applications: a comprehensive guide

Looking at my server code, here is how it appears: var data = { scripts: scripts, children:[<Comp1 />, <Comp2 />, <Comp3 />] }; // keeping smaller for easier example than reality var markup = ''; markup += '<scrip ...

"Storing a collection of PDF files in an array in TypeScript Angular - A step-by-step

Here we have an HTML code snippet that includes an input file element with Angular: <input type="file" class="btn btn-info" id="archivoPDF" #PDFfile value="Seleccionar PDF(s)" accept="application/pdf" multiple /> And this is the TypeScript code sni ...

JavaScript and jQuery experiencing difficulty rendering proper style and image in output display

I am currently working on code that extracts information from a JSON variable and displays it on a map. The code looks like this: marker.info_window_content = place.image + '<br/>' +"<h4>" + place.name + "</h4> ...

What is the best way to align content in the left center of a Paper component and ensure it stays that way on smaller devices?

Recently, I've been developing a component for my Goal Sharing social media platform. Here's what I have accomplished so far: https://i.stack.imgur.com/UDRim.png In an attempt to position the Avatar component along with two typography component ...

Exploring the Concept of Event Bubbling in ReactJS

Having recently delved into React.js, I've encountered a roadblock that has persisted for the past three days despite my attempts at various solutions. The issue revolves around two functions in my parent component named checkout: handleSeleteAddress ...

What is the reason for the Pointer Lock API entry displaying a significant number when the window is compressed?

Take a look at these two screenshots that illustrate the issue: The first screenshot demonstrates the correct behavior - the fullscreen mode works perfectly. However, in the second screenshot, a problem arises. Depending on the size of the browser window, ...

Issues arise with the loading of models while attempting to utilize Mocha testing

I'm currently in the process of using mocha for testing my express application. In terms of folder structure, it looks like this: myapp |-app |--models |-test |--mocha-blanket.js |--mocha |--karma |-server.js The server.js file serves as my express ...