Tips for sorting an array by property value and returning an array of objects

I have an array of objects containing the keys name and isPinned. My goal is to create a new array that stores only the country names based on the value of isPinned. For instance, if Australia and China are marked as true for isPinned, then the resulting array would be:

const countriesFiltered = ["Australia", "China"]

const countries = [
    { name: "Australia", isPinned: true },
    { name: "China", isPinned: true },
    { name: "India", isPinned: false },
  ];

Answer №1

To extract the names of pinned countries, you can use the .filter method with isPinned followed by .map with name

const namesOfPinnedCountries = countries
    .filter(country => country.isPinned)
    .map(country => country.name)

Answer №2

.filter() and .map() are commonly used methods, however, another approach is to utilize .reduce():

const countries = [
{ name: "Canada", isPinned: true },
{ name: "Mexico", isPinned: true },
{ name: "Brazil", isPinned: false },
];

const results = countries.reduce((acc, curr) => 
  curr.isPinned ? [...acc, curr.name] : acc, []);

console.log(results);

Answer №3

To achieve this, you can utilize the flatMap method:

const countries = [
    { name: "Germany", isPinned: true },
    { name: "Italy", isPinned: false },
    { name: "Spain", isPinned: true },
];
const pinnedCountries = countries
    .flatMap(country => country.isPinned ? country.name : []);
    
console.log(pinnedCountries);

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's the deal with Webpack and its development dependencies?

When working with NPM to create a basic web application, like using create-react-app, I am overwhelmed by the number of files in the node_modules directory. Most of these files are not even used as the application is still in its infancy. Are all these dep ...

Issue with Ag-Grid's getRowClass not locating the appropriate CSS styling

I am facing a simple challenge at the moment. My goal is to dynamically change the background color of my rows, with the intention of incorporating this feature when expanding or contracting groups. Currently, I am attempting to utilize gridOptions.getRow ...

Embed the Hero slides directly into the gatsby-image-plugin

Looking to transition my "Home hero slide" from hardcoded to dynamic using the gatsby-image-plugin. Visit my site for reference. Current "hardcoded" sections: HeroSlider.js New code here... HeroSlider.styles.js New code here... Slide.js New code ...

There seems to be an issue with Three.js: geometry.addEventListener isn't a recognized

I've been experimenting with Threejs to learn more about it, and I encountered an issue sooner than expected. I'm not sure if the problem lies in my code or within the framework itself (though I suspect it's on my end). The goal was to swap ...

What is the process for loading Syntax Highlighter on pages with pre tags?

As a Blogger, I often find myself in need of demonstrating codes on my blog. To achieve this, I have been using a Syntax Highlighter developed by Alex Gorbatchev. However, a recurring issue I face is that the files load on every single page of my blog, cau ...

Is there a way to verify the continuity of a string array and, if it's not continuous, how can it be removed?

For my current project, I have a table structured like this: String[] s1={"22","Software","1"}; String[] s2={"45","Software","2"}; ..... List<String[]> myL=new ArrayList<String[]>(); myL.add(s1); myL.add(s2); .... The goal now is to filter ou ...

The issue with $.parseJSON when encountering double quotes

Could someone please clarify why a JSON string with double quotes can disrupt the functionality of $.parseJSON? This example works: [{"type":"message","content":{"user":"tomasa", "time":"1321722536", "text":"asdasdasd"}}] And so does this one: [{"type" ...

Turn off Chrome's new tab preview thumbnails

Is there a method to prevent Google Chrome from displaying certain pages as thumbnails? I am inquiring because I am developing a website that contains confidential information. As it stands now, the sensitive data can be viewed in the thumbnail preview. ...

Send information and showcase it on the following screen using ReactJS

Having recently started using ReactJS for a front-end development project, I encountered a challenge that I need help with. I want to prompt the user for their name using an input field after a question like "What is your name?". Once the user inputs their ...

Iterating through an array of objects and extracting values from unspecified keys

Calculating which color holds a higher value in each array element of the data. Then adding the color with the higher value to an empty object, or increasing the count if already present. Finally, sorting the totals object from highest to lowest based on t ...

iOS/Safari browser experiencing issues with storing cookies in Express session, while Android is functioning correctly

For the past few weeks, I've been struggling with an issue while trying to login to my app on iOS. It seems that express-session is not storing cookies in the browser, preventing me from logging in. Oddly enough, I can successfully log in using my and ...

Personalize rejection message in the context of Promise.all()

Hello, I am currently working on customizing the error response in case a promise from an array fails. After referencing Handling errors in Promise.all, I have come up with the following code. However, I may need to make some adjustments to achieve the de ...

Javascript code requires server to have default text field values

Based on the choice made by a user, a text field box will either remain concealed or revealed: $("#aForm").on("change", function() { if ($(this).val() == "a") $("#textField").hide(); else $("#textField").show(); }); The issue arises when the ...

Open an external program

I'm currently working on a local web application and I want to be able to trigger an external application using a button click. I came across this code that works perfectly in an .html file with Internet Explorer, but when I try to implement it within ...

Placing the Cursor in a Document Editor

I'm currently working on a basic text editor and I'd like to add the feature where users can click on any text they've written to start editing it. To make this happen, I've set up a caret div to act as the cursor, positioning it accor ...

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

What is the method for locating line spacing within HTML code?

After posting a previous question, I am still on the quest to determine the exact position of each line of text within an element. While I was successful in identifying the css lineHeight attribute (as mentioned in the previous response), I encountered an ...

Using .setAttribute within a for-loop in JavaScript does not function as intended

I have encountered a minor issue with my JS-Script. I attempted to assign each element in an array a unique number, and these numbers were stored in another array. Initially, everything worked perfectly outside of the for-loop. var i = 0; document.getElem ...

What is the maximum number of rows that Handsontable can handle at once?

Issue encountered in queued task: Security check failed - Too many TRs. Please specify table height to enable scrollbars. at WalkontableTable._doDraw (client/libs/handsontable-0.10.5/jquery.handsontable.full.js?37b46fd989b9a974c3501865b51effd7adec37e4:1285 ...

Spacing and filtering strings in a React array

i am attempting to include space to the names filtered by the filter, but all the names are coming back without any space. How can I modify the filtered array to have space between each name? here is how it currently looks like - https://i.sstatic.net/AznK ...