How to convert string into two properties inside an array? - javascript

Here I am doing to convert the array into required format. output of parsedValues is ["abcdefgh(4034343), Mikhail(900002)"]
and Iam trying to convert it as ["abcdefgh(4034343)","Mikhail(900002)"]
How can I convert ["abcdefgh(4034343), Mikhail(900002)"] to ["abcdefgh(4034343)","Mikhail(900002)"] ?
private transformUser(userIdsString: any): string[] {
const parsedUserIdsArray = userIdsString;
console.log(parsedUserIdsArray);
const parsedValues = parsedUserIdsArray[4].userids;
console.log(parsedValues);
const splitValues = parsedValues.split(',');
console.log(splitValues);
const trimmedValues = splitValues.map(str => str.trim());
console.log(trimmedValues);
return trimmedValues;
}
The console.log(trimmedValues) is
(2) ["["abcdefgh(4034343)", "Mikhail(900002)"]"]
0: "["abcdefgh(4034343)"
1: "Mikhail(900002)"]"
length: 2
__proto__: Array(0)
Expected is :
(2) ["abcdefgh(4034343)", "Mikhail(900002)"]
0: "abcdefgh(4034343)"
1: "Mikhail(900002)"
length: 2
proto: Array(0)

You can use split on the string, to get an array from a separator (, in this case). If you have only one joined string, you can do...
["abcdefgh(4034343), Mikhail(900002), Someone(12934)"][0].split(', ')
To obtain a new array.
If the original array has multiple strings, you'll need to join all the arrays...
["abcdefgh(4034343), Mikhail(900002)", "Someone(12934)"]
.map(item => item.split(', '))
.reduce( (acc, item) => [...acc, ...item], [])

Try this
var input = ["abcdefgh(4034343), Mikhail(900002)"]
input.reduce(function(o,i){
var values = i.split(',');
if(values.length > 0){
o = o.concat(values);
}return o;},[]);
Output - ["abcdefgh(4034343)", " Mikhail(900002)"]

const trimmedValues = parsedValues[0].split(', ');

Related

Is there a way to get the keys in a dictionary as their original type?

I am very new to typescript and I have the following dictionary where the the keys and values are float arrays:
start_to_end_dict
> {-121.95131592,37.253239074: Array(2)}
> -121.95131592,37.253239074: (2) [-131.950349087, 47.253099466]
> [[Prototype]]: Object
I want to get a list of the keys as a list of arrays like this:
> [Array(2)]
> 0: (2) [-121.95131592, 37.253239074]
> length: 1
> [[Prototype]]: Array(0)
But then I get a list of strings instead:
Object.keys(start_to_end_dict)
['-121.95131592,37.253239074']
I noticed that values seems to get a list of arrays:
Object.values(start_to_end_dict)
> [Array(2)]
> 0: (2) [-131.950349087, 47.253099466]
> length: 1
> [[Prototype]]: Array(0)
As noted by other users in comments on your question: keys of objects are always strings in JavaScript. You can write a function to parse the string coordinates, and then iterate over the entries of the object, using it to parse the numeric coordinate values from each key, while accessing the (already parsed) values directly:
An explanation of the regular expression below can be accessed here.
TS Playground
type Coords = [number, number];
const coordsRegex = /^\s*(?<n1>-?(?:\d+\.)*\d+)\s*,\s*(?<n2>-?(?:\d+\.)*\d+)\s*$/;
function parseCoords (stringCoords: string): Coords {
const groups = stringCoords.match(coordsRegex)?.groups;
if (!groups) throw new Error('Coordinates format not valid');
const coords = [groups.n1, groups.n2].map(Number) as Coords;
return coords;
}
// This is the object value that you showed in the question:
const exampleData: Record<string, Coords> = {
'-121.95131592,37.253239074': [-131.950349087, 47.253099466],
};
for (const [key, value] of Object.entries(exampleData)) {
const keyCoords = parseCoords(key);
console.log({keyCoords, valueCoords: value});
}
Compiled JS from the TS playground above:
"use strict";
const coordsRegex = /^\s*(?<n1>-?(?:\d+\.)*\d+)\s*,\s*(?<n2>-?(?:\d+\.)*\d+)\s*$/;
function parseCoords(stringCoords) {
const groups = stringCoords.match(coordsRegex)?.groups;
if (!groups)
throw new Error('Coordinates format not valid');
const coords = [groups.n1, groups.n2].map(Number);
return coords;
}
// This is the object value that you showed in the question:
const exampleData = {
'-121.95131592,37.253239074': [-131.950349087, 47.253099466],
};
for (const [key, value] of Object.entries(exampleData)) {
const keyCoords = parseCoords(key);
console.log({ keyCoords, valueCoords: value });
}
Try this :
const start_to_end_dict = {
'-121.95131592,37.253239074': [-131.950349087, 47.253099466]
};
const arr = [];
Object.keys(start_to_end_dict).forEach(key => {
key.split(',').forEach(elem => arr.push(Number(elem)))
});
console.log(arr);

How to remove NaN from a string in an array

I have this array that is used by Svg to create a map. It contains one big string. The problem is that there are NaNs in the array and it is not able to read the array properly. How can I remove these NaNs?
Array [
"M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273 ...
]
array = ["M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273"]
you can map this array and use replace for each string
array = array.map(x => x.replace(/NaN/g,''))
array = ["M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273"]
array = array.map(x => x.replace(/NaN/g,''))
document.documentElement.innerHTML = array
you can map over the array & replace the cprrupted strings like this
const corruptedStrings = [
"M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273..."
];
const replaceWord = (originalWord, wordToMatch, newValue) => (
originalWord.replace(new RegExp(wordToMatch, 'g'), newValue);
)
const cleanedStrings = corruptedStrings.map(str => replaceWord(str, 'NaN', ''));

Convert an array of string key pairs to an object

I have this data structure:
[
'ecl:hzl byr:1926 iyr:2010,pid:221225902 cid:61 hgt:186cm eyr:2021 hcl:#7d3b0c',
'hcl:#efcc98 hgt:178 pid:433543520,eyr:2020 byr:1926,ecl:blu cid:92,iyr:2010',
'iyr:2018,eyr:2026,byr:1946 ecl:brn,hcl:#b6652a hgt:158cm,pid:822320101'
]
I'm looking to convert those array values to objects instead of strings. I understand I need to do a map with a split(' '), but unsure of the logic inside of there.
Desired output:
[
{ecl: 'hzl', byr: 1926},
{hcl: '#efcc98', byr: 1926}
]
etc. with all of the fields.
I've tried:
.map(values => { let pair = values.split(':'); obj[pair[0]] = pair[1]; return obj })
But seem to get the same object repeated over and over, from the first index of the array.
If you're looking to get each element of the array as a separate object then try this:
const input = [
'ecl:hzl byr:1926 iyr:2010,pid:221225902 cid:61 hgt:186cm eyr:2021 hcl:#7d3b0c',
'hcl:#efcc98 hgt:178 pid:433543520,eyr:2020 byr:1926,ecl:blu cid:92,iyr:2010',
'iyr:2018,eyr:2026,byr:1946 ecl:brn,hcl:#b6652a hgt:158cm,pid:822320101'
]
const output = input.map((string) => { // for each string in array
const pairs = string.split(/[\ ,]/); // split by space or comma
const object = {}; // create an object
for (pair of pairs) { // for each pair in string
const parts = pair.split(":"); // split by colon
if (parts.length == 2) { // if you get 2 parts after splitting
object[parts[0]] = parts[1]; // use the first part as a key and the second as a value
}
}
return object;
});
console.log(output);
Try this
array = array.map(val => {
var obj = {}
val.split(' ').forEach(keyValPair => {
var keyVal = keyValPair.split(':')
obj[keyVal[0]] = keyVal[1];
})
return obj;
})
You can use Object.fromEntries.
const arr = [
'ecl:hzl byr:1926 iyr:2010,pid:221225902 cid:61 hgt:186cm eyr:2021 hcl:#7d3b0c',
'hcl:#efcc98 hgt:178 pid:433543520,eyr:2020 byr:1926,ecl:blu cid:92,iyr:2010',
'iyr:2018,eyr:2026,byr:1946 ecl:brn,hcl:#b6652a hgt:158cm,pid:822320101'
];
const res = arr.map(x => Object.fromEntries(x.replace(/,/g, ' ')
.split(' ').map(y => y.split(':'))));
console.log(res);

JavaScript find "newest" version of a string

This is probably something really easy, but I can't think of any good solution here:
I have an array of strings:
let array = ['House1', 'House2', 'House3', 'Block1', 'Block2', 'BlockSpecial1'];
In time this array will change, but at any point I want to able to reduce that array to just the "newest" versions of the strings (based on the ending numbers, they may become 2- or 3-digit at some point), so what I want in the end would be:
['House3', 'Block2', 'BlockSpecial1']
Reduce the array to an object with the string as key, and the version as value. To get the string and version, you can use String.match(), and array destructuring. Then use Object.entries(), and Array.map() to combine it back to strings:
const array = ['House1', 'House2', 'House3', 'Block1', 'Block2', 'BlockSpecial1'];
const result = Object.entries(array.reduce((r, s) => {
const [, str, version] = s.match(/([A-Za-z]+)(\d+)/);
r[str] = (r[str] || 0) > version ? r[str] : version; // or r[str] = version if the versions are always in the right order
return r;
}, Object.create(null)))
.map(([k, v]) => k + v);
console.log(result);
You can do this actually very cleanly by creating a Map.
const array = ['House1', 'House2', 'House3', 'Block1', 'Block2', 'BlockSpecial1'];
const re = /^([^]+?)(\d+)$/;
const result = [...new Map(array.map(s => re.exec(s).slice(1)))]
.map(a => a.join(""));
console.log(result);
Here's the rundown...
In a .map() over the original array, divide each string between its text and number using a regex, and return an array that has only the captured parts.
Have the .map() result become the argument to the Map constructor. This creates the map with each first member of the sub array as each key, and the second as the value.
Because a Map must have unique keys, you only get the last key produced for each redundant key, which will also have the highest number.
Then convert that map to its remaining key/value entries, and join them back into a string.
Here's the same code from above, but breaking it into parts so that we can log each step.
const array = ['House1', 'House2', 'House3', 'Block1', 'Block2', 'BlockSpecial1'];
const re = /^([^]+?)(\d+)$/;
const keysVals = array.map(s => re.exec(s).slice(1));
console.log("original split:", keysVals);
const m = new Map(keysVals);
const mapKeysVals = [...m];
console.log("mapped keys vals", mapKeysVals);
const result = mapKeysVals.map(a => a.join(""));
console.log("result", result);
let tmp, name;
let array = ['House1', 'House2', 'House3', 'Block1', 'Block2', 'BlockSpecial1'];
let newest = array.sort((a, b) => b.match(/\d+$/)[0] - a.match(/\d+$/)[0]).sort().reverse()
.reduce((newArr, item) => (name = item.match(/.+[^\d]+/)[0], name != tmp && (newArr.push(item), tmp = name), newArr), []);
console.log(newest) //[ 'House3', 'BlockSpecial1', 'Block2' ]

How to convert string array to JSON array in Javascript?

I have string array like this:
"[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]"
How do I convert this either into a JSON Array or a JSON object like
{totRev:'248634.29858677526',....etc}
Use substring, split and reduce
str.substring( 1,str.length - 1 ) //remove [ and ] from the string
.split(",") //split by ,
.reduce( (a,b) => (i = b.split("="), a[i[0]] = i[1], a ) , {} );
Reduce explanation
Split b (element in the array such as totRev=248634.29858677526) by =
Assign the first item in the array as key to a (accumulator initialized as {}) and value as second item of the array
Return a
Demo
var str = "[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]";
var output = str.substring(1,str.length-1).split(",").reduce( (a,b) => (i = b.split("="), a[i[0].trim()] = i[1], a ) , {} );
console.log(output);

Categories

Resources