Use the .filter() method in JavaScript to generate an array containing abbreviated strings

Can anyone provide guidance on how to abbreviate an array of strings using the filter() method?

I am trying to use filter() with str.substring or another string method, but I'm not sure how to make it work properly.

In this code snippet, my goal is to return the first four characters of each name from the poshNames array. However, it seems like something is off.

Here's the JavaScript code:

let poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth"];
let nickNames;

nickNames = poshNames.filter(function(name){

  return name.str.substring(0,4);

});

Answer №1

To simplify the task at hand, consider utilizing the map method:

const poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth", "H"];
const nickNames = poshNames.map(name => name.substring(0,4));

console.log(nickNames);

Answer №2

Why not switch to using map instead of filter for a better result:

let poshNames = ["Benedict", "Seraphina", "Lysander", "Cordelia"];
let shortenedNames;

shortenedNames = poshNames.map(function(name) {
  return name.slice(0,4);
});

When using filter, you get an array with elements that meet the specified condition.

In contrast, by utilizing map, you receive an array with values determined by the function applied to each item in the original array.

Remember: Both methods yield new arrays while keeping the original intact.

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

fullpage.js not being used alongside bootstrap

On my webpage, I've integrated Bootstrap 4 and fullpage.js. However, when I apply the bootstrap col to sections, they stack vertically instead of appearing side by side. This is the HTML code: <div class="container-fluid position-relative"> &l ...

Tips for resetting the mapbox geocoder

Using the Mapbox Geocoder along with multiple select menus to customize a map has been my latest project. I am currently working on resetting the geocoder once a user selects an option from the menu, clearing the input field and removing the marker in the ...

Toggle the visibility of Div 1 and Div 2 with a click of the same button

Apologies for my lackluster title, but I couldn't come up with any better keywords. So here's what I need: I'm creating a chat application and on my page, there's a list of online users. When I click on User 1, a div with that user&apo ...

What is the best way to manage a promise in Jest?

I am encountering an issue at this particular section of my code. The error message reads: Received promise resolved instead of rejected. I'm uncertain about how to address this problem, could someone provide assistance? it("should not create a m ...

PHP JSON not working with Date Picker

My goal is to extract dates from a database and store them in a JSON format. These dates are intended to be used as unavailable dates in a datepicker. However, I am facing an issue where the datepicker is not displaying at all. checkDates.php ...

How can I modify my for loop with if else statements so that it doesn't just return the result of the last iteration in

Today is my first day learning JavaScript, and I have been researching closures online. However, I am struggling to understand how to use closures in the code I have written: function writeit() { var tbox = document.getElementById('a_tbox'). ...

I am encountering a situation while performing a Delete Jquery Ajax request where the response code is 200, however, the data is not being successfully deleted. What are some potential explanations for this issue?

Having issues with a DELETE request in my code. Here is what I have so far: $.ajax({ type : "DELETE", url : "/meds/dme-rest-api/resources/data-setup/deleteCheckList.json?" + $.param({"checkListId":currentCheckListId}), headers : {authToken : ...

Challenges with Expanse in Object-Oriented JavaScript

I'm currently working on incorporating objects from a JSON file into an array within my JavaScript object using the $.getJSON() function in jQuery. However, I've encountered scope challenges where the array elements appear to be defined inside th ...

Ways to extract information from an array using PHP

After splitting a comma-separated string variable into an array using explode, I am now facing difficulty in accessing the data stored in the array. This is the output of print_r function: print_r($values); // to view the structure of stored data //outp ...

Another inquiry regarding a city autocomplete field in a global setting

While I understand that this question may have been previously asked, I have spent several days searching without finding a satisfactory answer. Some websites, such as eventful.com, etc., have an autosuggest city field with cities from all over the world ...

How can you retrieve command line variables within your code by utilizing npm script in webpack?

I'm trying to access command line parameters from an npm script in my "constants.js" file. While I have been able to access parameters in the webpack.config.js file using process.env, it seems to be undefined in my app source files. The scenario con ...

How can MongoDB be used to query nested JSON structures?

My JSON data structure is as follows: "marks":{ "sem1" :{ "mark1":10, "total":100 }, "sem2":{ "mark2":20, "total":200 }, "sem3":{ "mark2":30, "total":300 } } I want to display the re ...

Issue with Build System CTA's/Callback function functionality not operational

I have encountered an issue with my build/design system. Although everything works fine during development, when I publish my package and try to use the callback function, it does not return the necessary data for me to proceed to the next screen. I tried ...

Does creating a form render the "action" attribute insignificant in an AJAX environment?

When submitting forms exclusively through AJAX, is there any advantage to setting the action attribute at all? I have yet to come across any AJAX-form guides suggesting that it can be left out, but I fail to see the purpose of including it, so I wanted t ...

Struggling to eliminate placeholders using regular expressions in JavaScript

In my dynamically generated table, I have some placeholders that need to be removed. These placeholders are in the format of {firm[i][j]}, where i and j are numbers. I attempted to use a regular expression in JavaScript to remove them, but it didn't ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

Retrieve information from an Express server using SweetAlert

Hi, I have created a web server using Node.js and Express. When I send a request to ip/test, it returns the text 'test' using res.send('test'). I am trying to fetch this text using sweetalert but I always encounter errors :( Here is t ...

Unable to complete the task of executing com.github.eirslett:frontend-maven-plugin:1.6:install-node-and-npm (install node and npm)

I'm encountering an issue with Maven that's been causing some trouble: [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.6:install-node-and-npm (install node and npm) on project xxx-frontend: Could not download Node.js: ...

The child outlet becomes empty after refreshing the URL with the ID sourced from the {{link-to}} method in Ember.js

I am facing a strange problem where the child outlet becomes empty every time I refresh the page with the id. I have a generated list using the {{link-to}} helper. <script type="text/x-handlebars" id="twod"> <div class="row"> ...

The strict-origin-when-cross-origin policy is enforced when submitting a POST request through a form to a specific route

Currently, I am diving into the world of Node.js, express, and MongoDB by reading Greg Lims's book. However, I've hit a roadblock when trying to utilize a form to submit data to a route that should then output the body.title of the form in the co ...