JavaScript Split string and create new arrays - javascript

I have below string
"ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0010124,1,1,1,1~100000003,1143748,0010165,1,1,1,1~100000004,,0010173,1,2,1,1~100000005,,0010199,2,2,2,1~100000006,,0010215,1,2,1,1~100000007,,0010306,0,2,1,1~100000008,1092546,0010355,1,1,1,1~100000009,1037977,,2,1,2,1~
I need to split by ~ and should create separate arrays with double quotes "". Below is expected
[
["ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"],
["100000000","1000048","0010041","1","1","1","1"],
["100000000","1000048","0010041","1","1","1","1"],
["100000000","1000048","0010041","1","1","1","1"],
]
This is what i have tried.
str.split('~').slice(2)
Which does not split to separate arrays. How to achieve the same. Thanks in Advance

You can first split with ~ and then split each sub array with ,. The code below is also removing the empty strings "". IF you want them included just remove the .filter(i => i)
EDIT:
removed the empty strings filter
const s = '"ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0010124,1,1,1,1~100000003,1143748,0010165,1,1,1,1~100000004,,0010173,1,2,1,1~100000005,,0010199,2,2,2,1~100000006,,0010215,1,2,1,1~100000007,,0010306,0,2,1,1~100000008,1092546,0010355,1,1,1,1~100000009,1037977,,2,1,2,1~'
const arr1 = s.split('~')
const arr2 = arr1.map(arr => {
arr = arr.replace(/\"/g, '')
return arr.split(',')
})
console.log(JSON.stringify(arr2, null, 2))

Related

How to combine all the arrays which are inside another array and delete the last symbol in each word?

There is a 2 dimensional array:
let userGroup = [
['user1-', 'user2-', 'user3-'],
['user4-', 'user5-', 'user6-'],
['user7-', 'user8-', 'user9-']
];
How to make a single array from it and delete the symbol "-" after each element?
So the output will be: ['user1, 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', etc...]
And also how to write a code which will do the same but with any number of inner arrays? For example if the "userGroup" array had more unexpected inner arrays with more users (['user11', 'user12', 'user13] etc.), what is the way to write a function which take the "userGroup" array and will do the same (delete the last element "-" in each element and combine all the elements in inner arrays into one array)?
Reduce is one way, can use also the new-ish flat method; by default it flattens only to single level but possible to define depth
userGroup.flat().map(item => item.slice(0, -1));
Try this:
console.log(userGroup.reduce((acc, curr)=> [...acc, ...curr], [])
.map(el => el.replace('-','')));
For a one liner, consider:
const mapped = userGroup.reduce((p,c) => p.concat(c), []).map(s => s.slice(0, s.length-1));
Try this
[].concat.apply([], userGroup).toString().split('-,');
Array.prototype.flat is the one you are looking for
userGroup.flat()
and then you will have the flat array for your array of arrays.
Then user the Array.prototype.map to convert the values as you like
userGroup.flat().map(m => m.replace('-', ''));
You need few things to achieve your goal.
.replace()
const u = 'user1-';
console.log(u.replace('-', ''));
.map()
const u = ["user1-", "user2-", "user3-"];
const m = u.map(i => i.replace("-", ""));
console.log(m);
.flat()
const u = [
["user1-", "user2-"],
["user3-", "user4-"]
];
console.log(u.flat());
So, combing all the 3 methods in a single statement, the below is the code:
let userGroup = [
['user1-', 'user2-', 'user3-'],
['user4-', 'user5-', 'user6-'],
['user7-', 'user8-', 'user9-']
];
let grouped = userGroup.flat().map(item => item.replace('-', ''));
console.log(grouped)

How to split pipe separated string into array of object

I have pipe separated string (sshshhs , 1) | (ee23es , 1) , I want to split and make an array of object . Result must be like [ {name:sshshhs,value:1},{name:ee23es,value:2} ]. I am new to JavaScript could someone please help me .
Thanks
Check out this code snippet
let myString = "(sshshhs , 1) | (ee23es , 1)";
// extract only the elements
let stringList = myString .split(/\) \| \(|\(|\)/);
// remove first and last empty elements, due to regex
stringList = stringList.slice(1,-1);
//split each element into an object
let objList = stringList.map(s => {
const [name, value] = s.split(',').map(el => el.trim());
return { name, value };
})
In this way with one regex you get rid of pipe and parenthesis. Then with a map you extract the name and value from each element.
You have multiple ways to transform your string into an array of object
One of them could be to split multiple times and use reduce to make the object
"(sshshhs , 1) | (ee23es , 1)"
.split('|') // here we first split with the principal key
.map(e => {
return [e.replace(/\(|\)/g, '')] // we create an object of your values to reduce it
.reduce((result, token) => {
const [name, value] = token.split(',').map(e => e.trim()); // we get the key/values by splitting it (and trimming it by the same time)
return {name, value}; // we then return the finded name and value
}, {})
})
This is definitly not the most efficient way to do it, but it will help you understand the mechanics behind split and reduce and help you create your own solution

How to convert string in an array?

From http response I received an object like this:
{"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
The key is an array...Is there a way in typescript to convert the key
"[3, company1]"
in an array like this
[3, "company1"]
?
You can combine Object.keys with map and transform the string to array with split
let data = {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
let keys = Object.keys(data)
.map(
el =>
el.replace('[', '')
.replace(']', '')
.split(',')
.map(el => el.trim())
.map(el => isNaN(parseFloat(el))
? el
: parseFloat(el))
)
console.log("Keys: ", keys)
Here is the fiddle:
https://jsfiddle.net/to38g6cb/1/
What do you want to convert the keys to?
if want to convert it to a normal array then the below should do.
const httpResponse = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
};
const convertedKeys = Object.keys(httpResponse).map(value => {
let keyArray = value.replace("[", "").replace("]", "").split(", ");
return [parseInt(keyArray[0]), keyArray[1]];
});
console.log(convertedKeys);
If the above is not what you wanted, please kindly rephrase your question again.
You can remove the first and last character using slice(1,-1) and split the string at /\s*,\s*/ (comma with optional spaces on either side).
Then convert the first part to a number and return the array
const input = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
}
const output = Object.keys(input).map(k => {
const [n, comp] = k.slice(1,-1).split(/\s*,\s*/)
return [+n, comp]
})
console.log(JSON.stringify(output))
It would have been easier if the company1 part were already quoted, so that you could just use JSON.parse. In fact, let's just do that! Put quotes around the company1 part with search and replace.
let key = `[3, company1]`;
let obj = JSON.parse(key.replace(/[$A-Z_]\w*/gi, '"$&"'))
console.log(obj);
Note: I'm guessing at what characters might be valid and went with something that looks vaguely like a JavaScript identifier. [$A-Z_]\w* Obviously not commas and right square brackets, due to deserialization ambiguity.

JS Array.splice return original Array and chain to it

I have a string with values like this a,b,c,d and want to remove a specific letter by index
So here is what I did str.split(',').splice(1,1).toString() and this is (obviously) not working since splice is returning the values removed not the original array
Is there any way to do the above in a one liner?
var str = "a,b,c,d";
console.log(str.split(',').splice(1,1).toString());
Thanks in advance.
You can use filter and add condition as index != 1.
var str = "a,b,c,d";
console.log(str.split(',').filter((x, i) => i != 1).toString());
Another strange solution. Destructure the array, remove the unwanted index, get an object and join the values of it.
var string = "a,b,c,d",
{ 1: _, ...temp } = string.split(',')
console.log(Object.values(temp).join(','));
The alternate way using regex replace
var str = "a,b,c,d";
console.log(str.replace(/,\w+/, ''))
Splice works in place, so oneliner is
const arr = "a,b,c,d".split(','); arr.splice(1,1); console.log(arr.toString());
If you want an string in a oneliner, you have to hardcode the index in a filter
console.log("a,b,c,d".split(',').filter((item, i) => i != 1).toString())
Or two slices (not performant at all)
const arr = "a,b,c,d".split(',')
console.log([...arr.slice(0,1),...arr.slice(2)].toString())

How do I convert an array inside an array to a string?

I'm new to programming. I am coding with javascript.
I want to convert an array with 3 arrays inside it to one single string and have spaces between each of the different arrays.
I want to turn this:
var myArray = [['example'], ['text'], ['hm']]
Into this:
var myString = 'example text hm'
I think you want that to be an array with []. If that's the case, this is a good use for reduce() combined with join() which will progressively build a concatenated array which you can then join:
let myArray = [['example'], ['text', 'text2'], ['hm']]
let str = myArray.reduce((all, arr) => all.concat(arr)).join(' ')
console.log(str)
Use nested for-each loops.
myString = "";
for each (row in myArray){
for each (column in row){
myString = myString + column;
}
}
In this specific case, you can use the standard Array.join(). This will invoke the sub-array's .toString() method. Usually it returns a string of the items, separated by commas, but Since you've got only a single item in each sub-array, you'll get that item in a string.
const myArray = [['example'], ['text'], ['hm']]
const result = myArray.join(' ')
console.log(result)
You can join them together using Array.join(' ')
const sentence = myArray.join(' ')
will return "example text hm"
The speech marks separated will keep the words separate and stop them joining together. If they are together it will join all the strings "exampletexthm"
I would also suggest that you use const or let instead of var. It can cause some issues. Article to look at

Categories

Resources