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?
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?
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);
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);
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});
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);
});
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);
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)
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 "%".
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); }));
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);
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 ...
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 ...
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' ...
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 ...
<script type="text/javascript" src="jquery-2.0.3.min.js"></script> <style> .canvas { position:relative; height:550px; width:400px; background:Yellow u ...
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 ...
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 ...
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 ...
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 ...
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 %>"> < ...
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 ...
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 ...
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 ...
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 ...
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 ...
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*": ...
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 ...
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]=> ...
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 ...
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& ...