Javascript - Removing commas from an array of string numbers - javascript

I currently have an array of strings that are numbers
data.dataArr = [0: " 1,431,417 "
​​
1: " 1,838,127 "
​​
2: " 679,974 "
​​
3: " 2,720,560 "
​​
4: " 544,368 "
​​
5: " 1,540,370 "]
I am attempting to remove the commas so my data returns 0: "1431417" , 1: 1838127 ...
After removing commas I am then mapping this array to convert it to an array of numbers and not strings. But when console.logging the finalArray that should return an array of numbers I am getting NaN I believe this is due to the part of removing the commas.
Here is my code:
let data = {
dataArr: [
" 1,431,417 ",
" 1,838,127 ",
" 679,974 ",
" 2,720,560 ",
" 544,368 ",
" 1,540,370 "
]
};
//removing commas
let arrData = data.dataArr.map(e => e.replace(/(,\s*)+/, ','));
let finalArr = arrData.map(Number);
console.log(finalArr)
alternatively I've tried :
let arrData = data.dataArr.replace(/,/g, "")
Which resulted in "data.dataArr.replace is not a function"

You can use number in same map callback function, g to remove all occurrence of ,
dataArr = [" 1,431,417 ", " 1,838,127 ", " 679,974 ", " 2,720,560 ", " 544,368 ", " 1,540,370 "]
let arrData = dataArr.map(e => Number(e.replace(/(,\s*)+/g, '').trim()));
console.log(arrData)

['1,234', '7,8,90,'].map(eachNo => {
return eachNo.split(',').join('')
});
Split() will split string where it will find ,(comma) and will return
an array of strings.
join() will operate on array of strings.

There also seems to be a space in your array which would be giving NaN, Remove everything other than digits and maybe a dot.
Try this regex:
e.replace(/[^\d.]/g, '');

Use Array.prototype.map()
const data = {};
data.dataArr = [
" 1,431,417 ",
" 1,838,127 ",
" 679,974 ",
" 2,720,560 ",
" 544,368 ",
" 1,540,370 ",
];
const numbersArray = data.dataArr.map(str => Number(str.replace(/\D/g, '')));
console.log(numbersArray)

Maybe like this:
var data = {};
data.dataArr =
[
" 1,431,417 ",
" 1,838,127 ",
" 679,974 ",
" 2,720,560 ",
" 544,368 ",
" 1,540,370 "
];
function array_to_numbers(_arr){
var out = [];
for(var key in _arr){
var el = _arr[key];
el = el.trim();
el = el.replace(new RegExp(',','g'), '');
el = parseInt(el)||0;
out.push(el);
}
return out;
}
console.log(array_to_numbers(data.dataArr));

You can .map() over the array and split up by , and then join them at "". You also need to wrap everything in Number to convert it to an number
let dataArr = [
" 1,431,417 ",
" 1,838,127 ",
" 679,974 ",
" 2,720,560 ",
" 544,368 ",
" 1,540,370 "
]
let result = dataArr.map(el => Number(el.split(",").join("")))
console.log(result)

let data = new Object();
data.dataArr = [ " 1,431,417 ",
" 1,838,127 ",
" 679,974 ",
" 2,720,560 ",
" 544,368 ",
" 1,540,370 "];
const finalArr = data.dataArr.map(x => x.replace(/[^0-9]/g, ''));
console.log(finalArr)

Related

Replace single quote ONLY FROM THE KEYS of object Javascript

hope everyone is fine, I have a tricky question, from an RPA app I get this object:
let data = {
Fecha: '2022-12-14T00:00:00',
Hora: '1899-12-31T16:14:00',
'Aten.': 73,
' Nro Ing ': 0,
Cerrada: 'S',
' ': ' ',
' Nombre Atenci¾n ': 'AMBULATORIA',
'EstadoHC.Electronica': ' - ',
Profesional: ' GARCIA CHAVERRA MADELEINE ',
Especialidad: ' MEDICINA GENERAL ',
Diagnostico: ' ENFERMEDAD CARDIACA, NO ESPECIFICADA ',
'Num.Cta': 0
}
As you can see, the key of the object, some of them are a little weird, what i want to do is replace the single quotes from the keys, to get the [Nombre Atenci¾n] value.
What I try is parser the object in a new object with JSON.parse and replace the spaces in the beginning and the end, like this:
let data2 = JSON.parse(JSON.stringify(data).replace(/"\s+|\s+"/g,'"'));
Then I try to iterate the second object, to get the specific value of the key mentioned before, after replace spaces and characters, but then I get undefined instead of "AMBULATORIA"
for(let dat in data2){
dat = dat.replace(/\s\s+/g, '').replace("¾", 'o');
console.log(dat.NombreAtencion)
}
Why I use a for to iterate "one single object" is because I get an array of objects like that one, so I have to use the same treatment to every object.
As you can see, the key of the object, some of them are a little weird, what i want to do is replace the single quotes from the keys
There are no single quotes in the object keys. In an object literal, you can put the name of the property in quotes (single or double). The quotes are just delimiters, not part of the property name. You only have to do that if the property name contains a character that isn't allowed in a property literal (which is true of all of your examples — spaces and . are perfectly valid in property names, but not property name literals).
So there's nothing to do, your object already has property names that don't have those quotes in them. You can tell by looking at the property names:
let data = {
Fecha: '2022-12-14T00:00:00',
Hora: '1899-12-31T16:14:00',
'Aten.': 73,
' Nro Ing ': 0,
Cerrada: 'S',
' ': ' ',
' Nombre Atenci¾n ': 'AMBULATORIA',
'EstadoHC.Electronica': ' - ',
Profesional: ' GARCIA CHAVERRA MADELEINE ',
Especialidad: ' MEDICINA GENERAL ',
Diagnostico: ' ENFERMEDAD CARDIACA, NO ESPECIFICADA ',
'Num.Cta': 0
};
console.log("Property names:");
for (const name of Object.keys(data)) {
console.log(name);
}
console.log("Value of property Aten.: ", data["Aten."]);
.as-console-wrapper {
max-height: 100% !important;
}
If you want to rationalize those property names so they're things you can use in property name literals (and so they follow the standard conventions for JavaScript property names), you could have a Map with the original name and the new name you'd like to use, and then create a new object with the new names for the properties:
let data = {
Fecha: "2022-12-14T00:00:00",
Hora: "1899-12-31T16:14:00",
"Aten.": 73,
" Nro Ing ": 0,
Cerrada: "S",
" ": " ",
" Nombre Atenci¾n ": "AMBULATORIA",
"EstadoHC.Electronica": " - ",
Profesional: " GARCIA CHAVERRA MADELEINE ",
Especialidad: " MEDICINA GENERAL ",
Diagnostico: " ENFERMEDAD CARDIACA, NO ESPECIFICADA ",
"Num.Cta": 0,
};
const nameMap = new Map([
["Fecha", "fecha"],
["Hora", "hora"],
["Aten.", "aten"],
[" Nro Ing ", "norIng"],
["Cerrada", "cerrada"],
[" ", "spaces"], // Or whatever
[" Nombre Atenci¾n ", "nombreAtencion"],
["EstadoHC.Electronica", "estadoHCElectronica"],
["Profesional", "profesional"],
["Especialidad", "especialidad"],
["Diagnostico", "diagnostico"],
["Num.Cta", "numCta"],
]);
const updated = Object.fromEntries(
Object.entries(data).map(([name, value]) => [nameMap.get(name) ?? name, value])
);
console.log(updated);
.as-console-wrapper {
max-height: 100% !important;
}
Or using a simple loop instead of Object.fromEntries, Object.entries, and map:
let data = {
Fecha: "2022-12-14T00:00:00",
Hora: "1899-12-31T16:14:00",
"Aten.": 73,
" Nro Ing ": 0,
Cerrada: "S",
" ": " ",
" Nombre Atenci¾n ": "AMBULATORIA",
"EstadoHC.Electronica": " - ",
Profesional: " GARCIA CHAVERRA MADELEINE ",
Especialidad: " MEDICINA GENERAL ",
Diagnostico: " ENFERMEDAD CARDIACA, NO ESPECIFICADA ",
"Num.Cta": 0,
};
const nameMap = new Map([
["Fecha", "fecha"],
["Hora", "hora"],
["Aten.", "aten"],
[" Nro Ing ", "norIng"],
["Cerrada", "cerrada"],
[" ", "spaces"], // Or whatever
[" Nombre Atenci¾n ", "nombreAtencion"],
["EstadoHC.Electronica", "estadoHCElectronica"],
["Profesional", "profesional"],
["Especialidad", "especialidad"],
["Diagnostico", "diagnostico"],
["Num.Cta", "numCta"],
]);
const updated = {};
for (const name of Object.keys(data)) {
const newName = nameMap.get(name) ?? name;
updated[newName] = data[name];
}
console.log(updated);
.as-console-wrapper {
max-height: 100% !important;
}
Or if you want to do it with some rules, here's an example treating . as a space, removing extraneous spaces, and converting to standard camelCase:
let data = {
Fecha: "2022-12-14T00:00:00",
Hora: "1899-12-31T16:14:00",
"Aten.": 73,
" Nro Ing ": 0,
Cerrada: "S",
" ": " ",
" Nombre Atenci¾n ": "AMBULATORIA",
"EstadoHC.Electronica": " - ",
Profesional: " GARCIA CHAVERRA MADELEINE ",
Especialidad: " MEDICINA GENERAL ",
Diagnostico: " ENFERMEDAD CARDIACA, NO ESPECIFICADA ",
"Num.Cta": 0,
};
function convertName(name) {
// Convert anything that isn't A-Za-z0-9_ to a space,
// and trim any leading/trailing spaces
name = name.replace(/[^\w]/g, " ").trim();
// If blank, bail early
if (!name) {
return "__unkown__";
}
// Split into words at a series of spaceds
let words = name.split(/ +/);
// Make the first word all lower-case, and make remaining words lower
// case except the first letter
words[0] = words[0].toLowerCase();
for (let n = 1; n < words.length; ++n) {
words[n] = words[n][0].toUpperCase() + words[0].substring(1).toLowerCase();
}
// Join the result
return words.join("");
}
const updated = Object.fromEntries(
Object.entries(data).map(([name, value]) => [convertName(name), value])
);
console.log(updated);
.as-console-wrapper {
max-height: 100% !important;
}
Or (again) using a simple loop instead of Object.fromEntries, Object.entries, and map:
let data = {
Fecha: "2022-12-14T00:00:00",
Hora: "1899-12-31T16:14:00",
"Aten.": 73,
" Nro Ing ": 0,
Cerrada: "S",
" ": " ",
" Nombre Atenci¾n ": "AMBULATORIA",
"EstadoHC.Electronica": " - ",
Profesional: " GARCIA CHAVERRA MADELEINE ",
Especialidad: " MEDICINA GENERAL ",
Diagnostico: " ENFERMEDAD CARDIACA, NO ESPECIFICADA ",
"Num.Cta": 0,
};
function convertName(name) {
// Convert anything that isn't A-Za-z0-9_ to a space,
// and trim any leading/trailing spaces
name = name.replace(/[^\w]/g, " ").trim();
// If blank, bail early
if (!name) {
return "__unkown__";
}
// Split into words at a series of spaceds
let words = name.split(/ +/);
// Make the first word all lower-case, and make remaining words lower
// case except the first letter
words[0] = words[0].toLowerCase();
for (let n = 1; n < words.length; ++n) {
words[n] = words[n][0].toUpperCase() + words[0].substring(1).toLowerCase();
}
// Join the result
return words.join("");
}
const updated = {};
for (const name of Object.keys(data)) {
const newName = convertName(name);
updated[newName] = data[name];
}
console.log(updated);
.as-console-wrapper {
max-height: 100% !important;
}

Parse Json Array on new lines correctly in StreamDeckSDK

I'm trying to take a JSON Array and display the full output, but nicely formatted. (see commented out section) Unfortunately the JSON array returns back with OBJECT then its output. So I stringify to fix the [Object, Object] error I was getting. But now everything is on one line. How do iterate through the array and put them on new lines?
Second issue I'm having is, I can't do 3 of the same functions as you notice in the uncommented section. I'd like to take each result and add a new line in between them.
function setTitleStatus(context, settings) {
$SD.api.setTitle(context, "Updating...");
getResults(result => resultCallback(result, context));
}
function resultCallback(result, context) {
if (!result.hasOwnProperty("Object")) {
$SD.api.setTitle(context, JSON.stringify(result));
console.log(JSON.stringify(result, '%c%s'));
return;
}
// This is where I'd like all 3 objects to be split on new lines.
// $SD.api.setTitle(context, result.Platform.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.Platform + " ")
// $SD.api.setTitle(context, result.PU.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.PU + " ")
// $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.EA + " ")
}
function getResults(updateTitleFn) {
let endPoint = "https://status.robertsspaceindustries.com/static/content/api/v0/systems.en.json";
$.getJSON(endPoint)
.done(function (response) {
updateTitleFn({
"Platform": response[0].status,
"PU": response[1].status,
"EA": response[2].status,
});
console.log("Platform", response[0].status)
console.log("PU", response[1].status)
console.log("EA", response[2].status)
})
}
Update
If I uncomment the sections this is what it shows. Its hard to tell but whats happening is, its taking replacing setTitle three times, and taking the last line. $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
"\n" + result.EA + " ")
Via Screenshot
To get nicely formatted output from JSON.stringify, supply the optional arguments:
JSON.stringify(obj, null, 2)
let arr = ["Pineapple", "Lemon", "Apple", "Orange", "Peach"];
document.getElementById('result').innerHTML =
'Stringify default: ' + JSON.stringify(arr) + '\n\n' +
'Stringify formatted: ' + JSON.stringify(arr, null, 2);
<pre id="result"></pre>

Uncaught SyntaxError: Unexpected number object [duplicate]

This question already has answers here:
How to access a numeric property?
(3 answers)
Closed 4 years ago.
var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';
var obj = JSON.parse(s);
document.getElementById("user").innerHTML =
"Name: " + obj.1 + " " + obj.2 + "<br>" +
"Location: " + obj.3;
Error from console:
Uncaught SyntaxError: Unexpected number
Use bracket notation to access numeric keys of an object:
const obj = { "1": "Sammy" };
console.log(obj["1"]);
Same goes for using some other character, for example -:
const obj = { "test-123": "works only with bracket notation" };
console.log(obj["test-123"]);
As gurvinder372 suggests, identifier cannot be numeric, you tried to access object's property with a number, which is wrong.
Correct Code
var s = JSON.parse('{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}');
document.getElementById("user").innerHTML =
"Name: " + s["1"] + " " + s["2"] + "<br>" +
"Location: " + s["3"];
you cannot have numbers after . (dot operator)
you should try using [].
var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';
var obj = JSON.parse(s);
document.getElementById("user").innerHTML =
"Name: " + obj[1] + " " + obj[2] + "<br>" +
"Location: " + obj[3];

Concat first item of array to first itiem of second array JavaScript

how can I concat more rationally first item of array to first of second array and so on? Basically automate console.log here is the code:
$("button#search").on("click", function(){
var inputVal = $("input#text").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + inputVal +"&limit=5&namespace=0&format=json&callback=?", function(json) {
var itemName = $.each(json[1], function(i, val){
})
var itemDescription = $.each(json[2], function(i, val){
})
var itemLink = $.each(json[3], function(i, val){
})
console.log(itemName[0] + " " + itemDescription[0] + " " + itemLink[0]);
console.log(itemName[1] + " " + itemDescription[1] + " " + itemLink[1]);
console.log(itemName[2] + " " + itemDescription[2] + " " + itemLink[2]);
console.log(itemName[3] + " " + itemDescription[3] + " " + itemLink[3]);
console.log(itemName[4] + " " + itemDescription[4] + " " + itemLink[4]);
})//EOF getJSON
});//EOF button click
I believe this is what you are looking for:
for (var i = 0; i < itemName.length; i++) {
console.log(itemName[i] + " " + itemDescription[i] + " " + itemLink[i]);
}
If arrays have the same length, you could use map
var result = $.map(json[1], function(i, val){
var row = val + " " + json[2][i] + " " + json[3][i];
console.log(row);
return row;
}
Also you can use that result later, e.g.
console.log(result[0]);
Using es6 you can do the following:
(in your getJson callback):
function (json) {
const [value, optionsJ, descriptionsJ, linksJ] = json;
let whatIwant = [];
// choose one to loop through since you know they will all be the same length:
optionsJ.forEach(function (option, index) {
whatIwant.push({option: option, description: descriptionJ[index], link: linksJ[index]});
});
// use whatIwant here**
}
Your new whatIwant array will then contain objects for each set.

How to replace multiple values in javascript?

I have some of this Code:
function writeIslamicDate(adjustment) {
var wdNames = new Array("Ahad","Ithnin","Thulatha","Arbaa","Khams","Jumuah","Sabt");
var iMonthNames = new Array("Muharram","Safar","Rabi'ul Awwal","Rabi'ul Akhir",
"Jumadal Ula","Jumadal Akhira","Rajab","Sha'ban",
"Ramadan","Shawwal","Dhul Qa'ada","Dhul Hijja");
var iDate = kuwaiticalendar(adjustment);
var outputIslamicDate = wdNames[iDate[4]] + ", " + (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " AH";
return outputIslamicDate;
}
document.write(writeIslamicDate());
Output : Ithnin, 23 Ramadan 1435 AH
?
I want to replace 23 with bengali number ২,৩ ///// or two, three
I watch and try a lot of but couldn't success.. Is there are any to solve this ?
Thanks.
I do like
var someString = (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " হিজরী";
var outputIslamicDate = somestring.replace(/1/g, "১").replace(/4/g, "৪");
return outputIslamicDate;
but it's not work...
Use regex and the global flag:
str.replace(/word/g, 'word2');

Categories