What is the best way to sort specific elements in an array?

Looking at this array:

let arr = [ 'file_1.jpg' , 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db' ]

I am interested in filtering out files with .jpg and .png extensions.

arr.filter() // expected result: [ 'file_1.png','file_2.png' ]

Answer №1

filteredArray = arr.filter(link => link.endsWith(".png") || link.endsWith(".jpg"));

Answer №2

Utilize Regular Expression for Filtering:

const fileArray = [ 'file_1.jpg' , 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db' ];

const regexPattern = /\.(png|jpg)$/; // select files ending with .png or .jpg
const filteredFiles = fileArray.filter((fileName) => regexPattern.test(fileName));

console.log(filteredFiles);

Answer №3

 let filteredLinks = arr.filter( link => link.endsWith(".png") || link.endsWith(".jpg"));

Answer №4

Unique Filter Function

The filter function in this unique example accepts a callback function that evaluates each item in the list and returns a boolean value.

An example is shown where a custom function uses a regular expression to determine if a given string is either a png or jpg.

Creating a Custom Filtering Expression

  • In this scenario, JavaScript regular expressions are defined within forward slashes: //
  • To match a dot character (any character) in a string requires escaping it with a backslash: /\./
  • To specify multiple options for matching strings, parentheses () and the pipe symbol (|) are used: /\.(jpg|png)/
  • To indicate that the match should be at the end of the text, add a dollar sign $ at the end: /\.(jpg|png)$/

The usage of the test function allows you to verify if a string adheres to the defined expression.

arr.filter(isJPEG);

function isJPEG(text) {
    return /\.(jpg|png)$/.test(text);
}

Custom Example Showcase

var arr = ['file_1.jpg', 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db'];

var filteredList = arr.filter(isJPEG);

console.log(JSON.stringify(filteredList));

function isJPEG(text) {
    return /\.(jpg|png)$/.test(text);
}

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

Having difficulty accessing the sound file despite inputting the correct path. Attempts to open it using ./ , ../ , and ../../ were unsuccessful

While attempting to create a blackjack game, I encountered an issue. When I click the hit button, a king card picture should appear along with a sound. However, the sound does not play and the error message Failed to load resource: net::ERR_FILE_NOT_FOUND ...

LiveValidation plugin causing issue with removing dynamically inserted elements

My form validation is powered by the Live Validation plugin. After submission, the plugin automatically inserts a line of code like this one: <span class=" LV_validation_message LV_valid">Ok</span> However, I encountered an issue when trying ...

Determine if a Numpy array exists within a collection of Numpy arrays - encountering issues with the .all()

Searching for a numpy array within a list of numpy arrays and printing 'Yes' if found is my current challenge. The array and list are defined as follows: many = [np.array([23, 34, 12]), np.array([23, 34, 23]), np.array([45, 23, 48])] test = np.a ...

Use a combination of the reduce and map functions in JavaScript to transform a one-dimensional array into a multi-dimensional array

Below is an array containing mySQL results: [ {"eventId":"84","shootId":"72","clubEventId":"253","clubId":"7"}, {"eventId":"84","sh ...

Nested Ajax calls within a loop

Here is the code structure I am working with: for (var x = 0; x < array1.length; x++){ (function(x) { $.ajax({ url : "http://someurl1.ru/"+array1[x]+"/", async: false, success : function(someresult1){ array2.length = 0; ...

Using Symfony2 to make an Ajax request in order to show a message based on a particular condition

As a novice in the realm of JavaScript and Ajax, I am struggling to find a way to display a message based on certain conditions. Let's consider a scenario where a user can adjust the quantity of a product they wish to purchase. While implementing thi ...

Updating text in JavaScript within a different HTML document

I am struggling to display the response from a REST request on an HTML page using JavaScript. However, the returned string is not being replaced on the HTML page as expected. JavaScript Code function sendDELrequest() { serviceID = $("#serviceID&q ...

Decouple configuration from primary execution within RequireJS

I have followed the instructions in the documentation to include requirejs using the data-main entry point. You can find more information here in the docs. <script data-main="js/app-main" src="js/lib/require.js"></script> The contents of my a ...

A code to ensure input values are always set to the maximum possible value

I recently developed a script that monitors the live value property of 3 <input> elements, correcting them if the live value is outside the specified range. However, I encountered an issue where the script automatically sets the value to the max as s ...

How can I use ajax to request data from PHP and retrieve several variables at once?

I'm exploring the use of JavaScript to call a PHP script that will then send multiple variables back to my JavaScript for manipulation purposes. Below is the JavaScript code I am using: $.ajax({ url: 'test.p ...

Retrieve the current exchange rate for the specified trading pair in United States Dollars

I am in the process of developing a bot that utilizes the Binance API. I am looking to obtain the USD value for each trading pair similar to what is displayed in their App (refer to screenshot). Is there a method available through their API to accomplish t ...

Customize time formatting in Angular to accommodate localized time formats

I am utilizing Angular's localization service version 8.3.28 to support English, Spanish (Mexico) with code es-MX, and Spanish (Spain) with code es-SP While using the date pipe: {{ foo.Date | date: 'shortDate' }} The dates are changing to ...

QUnit disregard error originating from the source

After writing tests for my Bacon.js functions using jQuery's qUni, I'm encountering an issue. Even though the outcome is correct and the equals() methods work as expected, qUnit marks the test as failed due to an error thrown by Bacon.js. Is the ...

Error encountered while attempting to attach event handler to <form> generated by .load using jQuery

My first question... I have a link on my page <a onclick="$('#mainbody').load('pages/login.php', tester());">Login</a> that generates this form: <form id="form"> <b>Email Address:</b> <input type= ...

Program sample experiences a sudden crash

I'm working on a program that allows the user to input characters to create a "shape" that is then printed on the screen based on the user's input. The program seems to work fine but it ends up freezing and displaying a "program not responding" m ...

Ways to retrieve the previous location of a mesh

Currently, I am working on writing a shader to create the motionBlur effect in WebGL using the three.js framework. I am trying to adjust this particular tutorial for implementing WebGL: and extracting the velocity value with GPUComputeRenderer. However ...

I find myself with just one button in my javascript function, but I actually need two

I'm currently working on a class assignment where I'm trying to create a javascript function that uses a button to display the value on a slider component. However, I'm running into an issue where only one button appears instead of two, even ...

What is the reason unboxed arrays do not qualify as a foldable instance?

Choosing the right data structure in Haskell can present some challenges, especially when working on my 2D grid application. I initially considered using UArray, but it seems that UArray does not implement foldable (neither in Data.Array.IArray nor Data.Ar ...

Ordering dynamically in AngularJS without relying on the second input variable

Check out my Codepen here (function(){ var app = angular.module('bars',[]); app.controller('BarController',function(){ this.bars = bars; }); app.controller('YearController',function ...

Eratosthenes' Filtering Method in Rust

Currently, I am working on implementing a sieve of Eratosthenes in Rust. I plan to use this code multiple times, so I am in the process of creating a function to execute the sieve. However, I have encountered an obstacle. I prefer using an array over a vec ...