What is the best way to sort through an array using JavaScript?

Here's an array for you:

values = ["10%", 1000, "5%", 2000]

I'm looking to split this into two separate arrays like so:

percentages = ["10%","5%"]
numbers = [1000,2000]

How can I achieve this using JavaScript array filter?

Answer №1

To effectively filter elements from an array, utilize the filter method alongside a callback function.

The filter() function constructs a fresh array containing only those elements that satisfy the conditions specified in the provided function.

Moreover, employ the typeof operator to determine the data type of each item within the array. The typeof operator enables you to identify the actual type of an operand.

let values = ["10%", "1000", "5%", "2000"];
let percentages = values.filter(function(item){
  return typeof item == 'string' && item.includes('%');
});
console.log(percentages);
let numbers = values.filter(function(item){
  return typeof item == 'number' || !isNaN(item);
});
console.log(numbers);

Answer №2

const values = ["20%", 500, "30%", 800];

const percentages = values.filter(val => val.toString().includes('%'));
const integers = values.filter(val => !val.toString().includes('%'));
console.log(percentages, integers);

Answer №3

Separate numbers and strings from a single array using advanced JavaScript techniques.

let items = ["10%", 1000, "5%", 2000];
var percentages = items.filter(e => isNaN(e));
var numbers = items.filter(e => !isNaN(e));
console.log({percentages, numbers});

Answer №4

If your array only contains strings, you can take advantage of regular expressions to filter out certain elements.

For finding percentages:

total.filter(function(element){
    return /^[0-9]+\%$/gi.test(element);
});

For absolute values:

total.filter(function(element){
    return /^[0-9]+$/gi.test(element);
});

Answer №5

To divide the array, you can make use of Array#reduce:

const items = ["10%", 1000, "5%", 2000];

const { whole, part } = items.reduce((arrays, element) => {
  const key = typeof element === 'number' ? 'whole' : 'part';
  
  arrays[key].push(element);
  
  return arrays;
}, { part: [], whole: [] });

console.log(whole);

console.log(part);

Answer №6

If you want a concise way to clear an array using ES2015 syntax, you can achieve this by filtering the elements based on a condition (in this example, we filter out elements greater than 2):

let MyArray = [1,2,3,4,5]

MyArray = [].concat(MyArray.filter(e => e > 2))

console.log(MyArray)

Answer №7

To achieve this, follow these steps:

let data = ["10%", 1000, "5%", 2000]

let numbersOnly = data.filter(function(element){
    if(typeof element == "number"){
        return 1;
    }
    return 0;
})
let percentages = data.filter(function(element){
    if(typeof element == "string" && element.match(/\%$/)){
        return 1;
    }
    return 0;
})
console.log(numbersOnly, percentages);

The first array filters out all the numbers.
The second array filters elements that are strings and end with a "%".

Answer №8

try out this snippet of code

$list = array('10%', '1000', '20%','2000');

//to display integers from the array

print_r(array_filter($list, function ($value) { return (stripos($value, '%') === false); }));

//to display % values from the array

print_r(array_filter($list, function ($value) { return (stripos($value, '%') == true); }));

Answer №9

const numbersAndPercentages = ["10%", "1000", "5%", "2000"];
const percentages = numbersAndPercentages.filter(function(item){
  return typeof item === 'string' && item.includes('%');
});
console.log(percentages);
const nonPercentageNumbers = numbersAndPercentages.filter(function(item){
  return typeof item === 'number' || !isNaN(item);
});
console.log(nonPercentageNumbers);

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

Translate data from two "contact form 7" date fields into JavaScript/jQuery to display the date range between them

NEW UPDATE: I was able to get it working, but the code is a bit messy. If anyone can help me clean it up, I would greatly appreciate it. <div class="column one-fourth" id="date-start">[date* date-start date-format:dd/mm/yy min:today+1days placeholde ...

Incorporating Product Identification to WHMCS Billing document

I'm having trouble adding a product ID to my WHMCS invoice. The code I currently have for that line is: <span class="title">{$LANG.invoicenumber}{*{else}{$LANG.proformainvoicenumber}{/if}*}{$invoicenum} - Service ID #{$invoiceitems.relid}</s ...

Setting the axios baseURL configuration globally in Nuxt.js

When starting a new project, you can use the following command: npm init nuxt-app <project-name> To set up the baseURL for axios, refer to this guide: npm install @nuxtjs/axios In your nuxt.config.js file: modules: [ '@nuxtjs/axios' ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

The onDrop event will redirect to a URL specifically in the Firefox browser

<script type="text/javascript" src="jquery-2.0.3.min.js"></script> <style> .canvas { position:relative; height:550px; width:400px; background:Yellow u ...

Looking for assistance in adding some animated flair to your website as users scroll

I don't have much experience in animation but I would like to create some animation effects on scroll down. Can anyone provide suggestions? I attempted using SVG paths, but it didn't work out as expected. What I am aiming for is that when a visi ...

Issue with retrieving the current location while the map is being dragged

How can I retrieve the current latitude and longitude coordinates when the map is dragged? I've tried using the following code: google.maps.event.addListener(map, 'drag', function(event) { addMarker(event.latLng.lat(), event.la ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

Issue with Adding Additional Property to react-leaflet Marker Component in TypeScript

I'm attempting to include an extra property count in the Marker component provided by react-leaflet. Unfortunately, we're encountering an error. Type '{ children: Element; position: [number, number]; key: number; count: number; }' is n ...

What's causing Angular to not display my CSS properly?

I am encountering an issue with the angular2-seed application. It seems unable to render my css when I place it in the index.html. index.html <!DOCTYPE html> <html lang="en"> <head> <base href="<%= APP_BASE %>"> < ...

Having trouble locating the module '.outputserver ode_modulespiniadistpinia' in Nuxt3 and Pinia?

I recently integrated Pinia into my Nuxt3 project, and while everything works fine in development mode, I encountered an error when trying to access the application in production mode resulting in the website freezing. [h3] [unhandled] H3Error: Cannot find ...

Incorporate a "Back" button following the removal of the navigation bar in a Meteor-Ionic

When working on a Meteor-Angular-ionic app, I encountered a situation where I needed to hide the nav-bar in a template to create a full-screen view using the following code: <ion-view hide-nav-bar="true"> However, I then faced the challenge of addi ...

Utilize JavaScript to load external JavaScript libraries and scripts

Currently, I am working on developing a console application using JavaScript/Node.js. However, when compiling the script.js file, I encounter a ReferenceError: $ is not defined issue. //user input from command line var readline = require('readline&ap ...

Is it possible for .getElementByClassName to identify Ajax.GET elements?

I've run into a problem that I need help with: The issue arises when I have an API that makes an Ajax GET request. In the success function, it creates a button, a div, and several span elements with information inside, each with its own class. The GE ...

Using JavaScript to manage form input values in React

I am currently coding a basic application using NextJS and bulma CSS. The snippet below shows the form I am working on: const MyPage = () =>{ const [firstName, setFirstName] = useState('') const [secondName, setSecondName] = useState('&ap ...

Filtering JSON data with JavaScript

Looking to group data in AngularJS using UnderscoreJS. Here is the JSON data: data = [ { "Building*": "Building A", "Wing*": "Wing C", "Floor*": "Floor 3", "Room Name*": "Room 3", "Room Type*": ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

Tips for inserting data into a specific position within an array

I am working with an array that currently contains only usernames, which I have added using array_push within a foreach loop: array(4) { [0]=> string(13) "Username1" [1]=> string(10) "Username2" [2]=> string(12) "Username3" [3]=> ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

Error encountered with the OffsetWidth in the Jq.carousel program

I am encountering an issue that I cannot seem to figure out. Unexpected error: Cannot read property 'offsetWidth' of undefined To view the code in question, click on this link - http://jsfiddle.net/2EFsd/1/ var $carousel = $(' #carouse& ...