Skip to content

Instantly share code, notes, and snippets.

@bhaireshm
Last active February 24, 2025 09:24
Show Gist options
  • Save bhaireshm/67fdacc8a7ef52e0334e9782e47ee207 to your computer and use it in GitHub Desktop.
Save bhaireshm/67fdacc8a7ef52e0334e9782e47ee207 to your computer and use it in GitHub Desktop.
Check and convert array of strings to array of number or object's string value to integer.
/**
* @param {String} s
* @returns number
* @example console.log(toNumber("-23.32"))
*/
const toNumber = (s, returnStrings = false) =>
isNaN(Number(s)) ? (returnStrings ? s : console.error(`${s} NaN`)) : Number(s);
/**
* @param {Array or Object} data - required
* @param {String} str - key names separated by comma (optional)
* @returns array or object
* @example strToNum(["3","4",3,"7",8])
* @example strToNum({ a:2, b:"4", c:"5" }, "c,b")
*/
const strToNum = (data, str) => {
if (typeof data == "object") {
if (!str && data.length > 0) return data.map((d) => toNumber(d, true));
if (str && data.length == undefined) {
const out = {};
Object.entries(data)
.map((d) => {
if (str.split(",").some((s) => s == d[0])) d[1] = toNumber(d[1], true);
return d;
})
.forEach((a) => (out[a[0]] = a[1]));
return out;
}
}
};
@bhaireshm
Copy link
Author

ez.js is more than just a library; it's a coding companion that simplifies complex tasks. Whether you're dealing with arrays, numbers, objects, or strings, ez.js has got your back! Say goodbye to coding hassles and hello to streamlined JavaScript magic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment