Convert an array which contains strings into key value pairs - javascript

I have a string "101-2000-10-102-2000-15" which I have to map as key: 101 values: {2000, 10}.
With the below code I am able to get the output as 101 => 2000 but I am unable to the one remaining value.
This is the Code:
let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => x.split("-")));
console.log(compartmentMap);
My input: "101-2000-10-102-2000-15"
Desired Output: {101 => {2000,10}, 102 => {2000,15}}

You need to get an array of values as well.
let myString = "101-2000-10-102-2000-15"
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = new Map(strArray.map(x => {
const [k, ...v] = x.split("-");
return [k, v];
}));
console.log(Array.from(compartmentMap));

I think I'd be fairly pedestrian about it:
const result = new Map();
const rex = /(\d+)-(\d+)-(\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
result.set(match[1], [match[2], match[3]]);
}
That's assuming you want the 2000, 10 part as an array.
Live Example:
const myString = "101-2000-10-102-2000-15"
const result = new Map();
const rex = /(\d+)-(\d+)-(\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
result.set(match[1], [match[2], match[3]]);
}
console.log([...result.entries()]);
Or with more meaningful names via named capture groups and destructuring:
const result = new Map();
const rex = /(?<key>\d+)-(?<value1>\d+)-(?<value2>\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
const {key, value1, value2} = match.groups;
result.set(key, [value1, value2]);
}
Live Example:
const myString = "101-2000-10-102-2000-15"
const result = new Map();
const rex = /(?<key>\d+)-(?<value1>\d+)-(?<value2>\d+)/g;
let match;
while ((match = rex.exec(myString)) !== null) {
const {key, value1, value2} = match.groups;
result.set(key, [value1, value2]);
}
console.log([...result.entries()]);
Or with the new matchAll and destructuring:
const rex = /(\d+)-(\d+)-(\d+)/g;
const result = new Map(
[...myString.matchAll(rex)].map(
([, key, value1, value2]) => [key, [value1, value2]]
)
);
Live Example:
const myString = "101-2000-10-102-2000-15"
const rex = /(\d+)-(\d+)-(\d+)/g;
const result = new Map(
[...myString.matchAll(rex)].map(
([, key, value1, value2]) => [key, [value1, value2]]
)
);
console.log([...result.entries()]);

One approach would be to just split the string, and then perform a reduce() operation for every three elements:
const s = '101-2000-10-102-2000-15';
const result = s.split('-').reduce((r, v, i, a) =>
i % 3 ? r : {...r, [v]: a.slice(i + 1, i + 3)}, {});
console.log(result);

Slight change to your code, use reduce instead of map.
let myString = "101-2000-10-102-2000-15";
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
let compartmentMap = strArray.reduce((acc, curr) => {
const [a, b, c] = curr.split("-");
return Object.assign(acc, { [a]: [b, c] });
}, {});
console.log(compartmentMap);

Actually, I figured a better which gives out a Map with exact key-value pairs. All I need is to pass a Map and My array to it and it spits out the map with the key-values.
const myString = '101-2000-10-102-2000-15';
let strArray = myString.match(/[^-]+-[^-]+-[^-]+/g);
console.log(strArray);
const compartmentMap = (someMap, someArray) => (someArray.map(x => { console.log(x)
const [a, b, c] = x.split("-");
someMap.set(a, {b,c});
}));
const x = new Map();
compartmentMap(x, strArray);
console.log(x);

Related

Create new array with matched values with it's sum in javascript

I have below type of array, now I want to match the value before underscore and sum the values after underscore and store it into the new array with matched key.
let myarray = [];
myarray[0] = "25_5";
myarray[1] = "125_15";
myarray[2] = "25_10";
myarray[3] = "125_30";
Expected output
matchedArr[25] = 15
matchedArr[125] = 45
I tried below code
this.myarray.forEach((i) => {
let arr = i.split("_");
let key = arr[0];
let price = arr[1];
console.log(key+' = '+price);
});
You can do this with a fairly simple reduce
let myarray = [];
myarray[0] = "25_5";
myarray[1] = "125_15";
myarray[2] = "25_10";
myarray[3] = "125_30";
const result = myarray.reduce( (acc, i) => {
const [key,value] = i.split("_");
acc[key] = (acc[key] || 0) + parseInt(value,10);
return acc;
},{})
console.log(result)
This will do sort of what you want
Are you sure you want the output to be an array though?
let myarray = [];
myarray[0] = "25_5";
myarray[1] = "125_15";
myarray[2] = "25_10";
myarray[3] = "125_30";
let matchedArray=myarray.reduce((a,i)=>{
const [k,v]=i.split('_');
a[k]=(a[k]||0)+ +v;
return a;
},[]);
console.log(matchedArray);
if you replace ,[]) with ,{}) you'll get a much more useful result

Convert array of strings to object with params and values

I have next array with strings:
['val1=123','val2=456']
How I can split it to object with params and values?
{
val1: 123,
val2: 456,
}
const recordStrings = ['val1=123', 'val2=456']
const record = Object.fromEntries(
recordStrings.map(str => str.split('='))
)
console.log(record)
Explanation:
recordStrings.map(str => str.split('=')) returns [[val1, 123], [val2, 456]].
Object.fromEntries(entries) creates an object from an array containing [key, value] tuples.
You can try with reduce method, it's really helpful to convert an array to any others data type like an object, string, number.
const arr = ['val1=123','val2=456'];
const items = arr.reduce((total, item) => {
const [key, value] = item.split('=');
if (key) {
total[key] = value
}
return total;
}, {})
console.log(items);
Split the strings in the array and convert the array to an object:
const res = ['val1=123','val2=456'];
const result = Object.fromEntries(res.map(x => {
const [l, r] = x.split('=');
return [l, +r];
}));
console.log(result);
let obj = {};
let arr = ['val1=123', 'val2=456'];
arr.forEach(i => {
let x = i.split('=');
obj[x[0]] = parseInt(x[1]);
});
console.log(obj);
let arr = ['val1=123', 'val2=456']
let object = {}
for (let i = 0; i < arr.length; i++) {
var split = arr[i].split("=")
object[split[0]] = split[1]
}
console.log(object); // { val1: '123', val2: '456' }
let arr = ['val1=123','val2=456'];
arr.forEach(str => {
let arrStr = str.split('=');
eval(arrStr[0] + '= ' + arrStr[1] + ';');
})
console.log(val1, val2);
OR
let arr = ['val1=123','val2=456'];
arr.forEach(str => {
let arrStr = str.split('=');
window[arrStr[0]] = arrStr[1];
})
console.log(val1, val2);

Convert Array to Object with special case

how can i turn this array to an object like below
let arr = ["key1:value1","key2,value2"]
to
{
"key1":"value1",
"key2":"value2"
}
Split by either colons or commas, then pass to Object.fromEntries:
const arr = ["key1:value1","key2,value2"];
const obj = Object.fromEntries(
arr.map(str => str.split(/[:,]/))
);
console.log(obj);
Try using reduce:
const arr = ["key1:value1","key2,value2"];
const object = arr.reduce((obj, item) => {
const colon = item.split(':');
if (colon.length === 2) {
obj[colon[0]] = colon[1];
return obj;
}
const comma = item.split(',');
if (comma.length === 2) {
obj[comma[0]] = comma[1];
return obj;
}
return obj;
}, {});
or forEach
const arr = ["key1:value1","key2,value2"];
const object = {};
arr.forEach(item => {
const colon = item.split(':');
if (colon.length === 2) {
obj[colon[0]] = colon[1];
}
const comma = item.split(',');
if (comma.length === 2) {
obj[comma[0]] = comma[1];
}
});
You can try with reduce()
let arr = ["key1:value1","key2,value2"];
var res = arr.reduce((a,c) => {
var k = c.split(/[:,]/)[0];
var v = c.split(/[:,]/)[1];
a[k] = v;
return a
},{});
console.log(res);

How to use split on a string and then convert it to object in Javascript

I have an array:
let arr = ["a=1", "b=22", "c=11"];
And I want to split the string inside array so it becomes an object later, which will look like:
{a: 1, b: 22, c: 11}
Can I somehow do that
You could split the string an map new objects. Later assign all objects to a single object.
var array = ["a=1", "b=22", "c=11"],
object = Object.assign(
...array.map(s => ((k, v) => ({ [k]: +v }))(...s.split('=')))
);
console.log(object);
you can use array.forEach, so you wont be creating an array instead you will iterate through the array, and you can take each item and split so it will create an array
like item = ["a", "1"], you can assign the key as a to the object which is the first index and value is second index,The value is string so you can convert to number and return it.
let arr = ["a=1", "b=22", "c=11"];
var obj = {}
arr.forEach(o => {
var item = o.split("=");
return obj[item[0]] = Number(item[1])
})
console.log("required obj", obj)
You can use array#map with Object.assign() to create your object. string#split each word on = and generate the object.
let arr = ["a=1", "b=22", "c=11"],
result = Object.assign(...arr.map(word => {
let [key,value] = word.split('=');
return {[key] : +value};
}));
console.log(result);
You can also use array#reduce.
let arr = ["a=1", "b=22", "c=11"],
result = arr.reduce((r,word) => {
let [key,value] = word.split('=');
r[key] = +value;
return r;
}, {});
console.log(result);
Here, try this
let arr = ["a=1", "b=22", "c=11"];
const obj = {}
arr.forEach(i => {
const splitted = i.split('=')
obj[splitted[0]] = splitted[1]
} )
console.log(obj)

could i use higher function on this?

this is a code that I want to know if I want to use in some other functions, such ForEach, map, filter, or what else?
is that possible?
const val = 'Mike,Mike#mail.com,male'
const split = val.split(',')
console.log(split) //to check
const newObj = {}
newObj.name = split[0]
newObj.email = split[1]
newObj.gender = split[2]
console.log(newObj)
const val2 = 'name:John,email:John#mail.com'
const split2 = val2.split(',')
console.log(split2) //to check
const newObj2 = {}
for(var i = 0; i < split2.length; i++) {
var data = split2[i].split(':')
newObj2[data[0]] = data[1]
}
console.log(newObj2)
want to make the code more clean and short
const val = 'Mike,Mike#mail.com,male'
const [name, email, gender] = val.split(',')
console.log({name, email, gender})
const val2 = 'name:John,email:John#mail.com'
const splitByColon = term => {
const [key, value] = term.split(':')
return {[key]: value}
}
console.log(
val2
.split(',')
.reduce((acc, term) =>
({...acc, ...splitByColon(term)}), {})
)
Another way could be
const val = 'name:Mike,email:Mike#mail.com,gender:male'
const obj = {}
val.split(',')
.map(prop => prop.split(':'))
.forEach(([key, value]) => {
obj[key] = value
})
console.log(obj)

Categories

Resources