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', ''));
Related
Hi below is array of strings
const arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
"some-domain/4/item/5/subitem/1/",
]
i have to filter those strings that start with string "item/3/" or ends with string "item/3/"
so from above array expected filtered array is like below,
const filtered_arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
]
from the filtered array i want to get the number after "/item/". so from above filtered array the expected output is
const arr_ids = ["1", "2", "3"]
what i have tried,
i have used below to match those strings that start or end with /item/3/
const filtered_arr = arr.map(str) => {
return str.match(/item\/[0-9](\/)?$/g);
}
this gives the filtered_arr
const filtered_arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
]
but how do i map through each array item and get the number after string "/item/".
could someone help me with this. thanks.
Use filter to filter paths either starting or ending in item/\d+/. Then use map to extract the item number from each matching path.
const arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
"some-domain/4/item/5/subitem/1",
];
var output = arr.filter(x => x.match(/^item\/\d+|\bitem\/\d+\/$/))
.map(x => x.match(/(?<=^item\/)\d+|(?<=\bitem\/)\d+(?=\/$)/)[0]);
console.log(output);
This may help:
const filtered_arr = arr.map(str) => {
const match = str.match(/\/item\/(\d)/);
return(match[1]);
}
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);
I have big array, which looks like this example:
let array = ['aa-we', 'aa-we__qq', 'aa-we__qw', 'gsPlsOdd', 'bc-po-lp', 'bc-po-lp--ps', 'de', 'de__io', 'de__sl', 'de--xz', 'ccsDdd'];
i want split this array into small arrays by values:
let array = [
['aa-we', 'aa-we__qq', 'aa-we__qw'],
['bc-po-lp', 'bc-po-lp--ps'],
['de', 'de__io', 'de__sl', 'de--xz']
]
// and camelcase strings should be removed
Values in array have syntax like BEM selectors, so if the prefix of different strings is the same, they should be wrapped in a single array.
How can i do this, if possible, without additional libraries?
Thanks for the help or tips!
console.clear()
let data = [
"aa-we",
"aa-we__qq",
"aa-we__qw",
"gsPlsOdd",
"bc-po-lp",
"bc-po-lp--ps",
"de",
"de__io",
"de__sl",
"de--xz",
"ccsDdd",
];
resultO = data.reduce((acc, val, idx) => {
if (val.match(/[A-Z]/)) {return acc;}
const sel = val.replace(/^(.*)(__|--).*$/g, "$1");
acc[sel] = acc[sel] || [];
acc[sel].push(val)
return acc;
}, {})
resultA = Object.values(resultO)
console.log(resultA)
I'd do something like this and then filter out what you don't want.
let array = ['aa-we', 'aa-we__qq', 'aa-we__qw', 'gsPlsOdd', 'bc-po-lp', 'bc-po-lp--ps', 'de', 'de__io', 'de__sl', 'de--xz', 'ccsDdd'];
array = array.filter((a) => !a.match(/[A-Z]/))
let result = groupBy(array, (str)=> str.split(/[-_]/)[0])
console.log(Object.values(result))
function groupBy(arr, condition) {
return arr.reduce((result, current) => {
const key = condition(current);
(result[key] || (result[key] = [])).push(current)
return result
}, {})
}
The algorithm can be as follows:
Create Map<Prefix,ValuesArray>
For each element in array:
Get it's prefix, e.g. "ab", skip element if invalid (e.g. no prefix exist or camel case)
Add to corresponding hashed bucket
Join values from Map into one array
JS has all the primitives to implement this, just take a look at Map/Object for hashing and Array (map/filter/reduce) for processing.
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' ]
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);