I am Trying to convert the array [ '9:00', '9:40', '9:50', '11:00', '15:00', '18:00' ] to [ '900', '940', '950', '1100', '1500', '1800' ] in javascript.
CodePudding user response:
You can do it in this way:-
let oldArray = ['9:00', '9:40', '9:50', '11:00', '15:00', '18:00'];
let newArray = oldArray.map(elem => elem.replace(':',''));
console.log(newArray);
CodePudding user response:
What you're looking for is the .map() function. This function iterates over all items in the array, allowing you to execute code on said iterations. Use what I've provided below.
const arrayOfTimestamps = [ '9:00', '9:40', '9:50', '11:00', '15:00', '18:00' ];
const formattedTimestamps = arrayOfTimestamps.map(time => time.replace(/:/g, ''))
As an explanation, .map() iterates over each item, and the time is being handled by regex. the /g aka global flag tells the regex to remove all semicolors's from the strings.
For more information on how .map() works, here.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
CodePudding user response:
var list = [ '9:00', '9:40', '9:50', '11:00', '15:00', '18:00' ];
for (var i = 0; i < list.length; i )
{
list[i] = list[i].replace(':', '');
}
CodePudding user response:
First, you need a regular expression for this similar to this one:
var regExpStuff = /[/:]/;
var array = removeItem(unique, regExpStuff);
Then you need a remove function with splice method and using the regex above:
function removeItem(originalArray, itemToRemove) {
var j = 0;
while (j < originalArray.length) {
if (originalArray[j] == itemToRemove) {
originalArray.splice(j, 1);
} else { j ; }
}
return originalArray;
}
CodePudding user response:
Use map to apply a callback to each element of the array, and return the processed result.
let arr = ['9:00', '9:40', '9:50', '11:00', '15:00', '18:00']
arr = arr.map(v => v.replace(/:/g, '')
Flag g for Regex will replace all : occurrences. Without it only the first : will be removed.
