I have a string as follows
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
I want to get three arrays from above string as follows
var arr1 = ["series-3","series-5","series-6"];
var arr2 = ["a3","a4","a5"];
var arr3 = ["class a", "class b"];
What regex should I use to achieve this?
Can this be done without regex?
Use String#split() method
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// split string based on comma followed by [
var temp = str.split(/,(?=\[)/);
// remove [ and ] from string usning slice
// then split using , to get the result array
var arr1 = temp[0].slice(1, -1).split(',');
var arr2 = temp[1].slice(1, -1).split(',');
var arr3 = temp[2].slice(1, -1).split(',');
console.log(arr1, arr2, arr3);
Or same method with some variation
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Remove [ at start and ] at end using slice
// and then split string based on `],[`
var temp = str.slice(1, -1).split('],[');
// then split using , to get the result array
var arr1 = temp[0].split(',');
var arr2 = temp[1].split(',');
var arr3 = temp[2].split(',');
console.log(arr1, arr2, arr3);
RegEx and String methods can be used. It's better to create an object and store individual arrays inside that object.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Match anything that is inside the `[` and `]`
var stringsArr = str.match(/\[[^[\]]*\]/g);
// Result object
var result = {};
// Iterate over strings inside `[` and `]` and split by the `,`
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var stringsArr = str.match(/\[[^[\]]*\]/g);
var result = {};
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
To create the global variables(Not recommended), just remove var result = {}; and replace result by window in the forEach.
I would prefer to do it like this
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]",
arrs = str.match(/[^[]+(?=])/g).map(s => s.split(","));
console.log(arrs);
Just for the fun of it, another way where we add the missing quotes and use JSON.parse to convert it to a multidimensional array.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var result = JSON.parse("[" + str.replace(/\[/g,'["').replace(/\]/g,'"]').replace(/([^\]]),/g,'$1","') + "]");
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);
Related
I want all index value that have data in array after ":" & split it to different Array at same index number. I am able to change data for one index value but its not changing for all value
var Array = ["Alice:", "John:654", "Bob:123"];
** After Split **
var Array = ["Alice:", "John:", "Bob:"];
var new array = ["", "654", "123"];
<script>
var array = ["Alice:", "John:654", "Bob:123"];
var el = array.find(a =>a.includes(":"));
let index = array.indexOf(el);
const newArray = el.split(':')[0] + ':';
var array2 = ["", "", ""];
array2[index] = newArray;
document.getElementById("demo").innerHTML = "The value of arry is: " + el;
document.getElementById("demo2").innerHTML = "The index of arry is: " + index;
document.getElementById("demo3").innerHTML = "split value: " + newArray;
document.getElementById("demo4").innerHTML = "new arr: " + array2;
</script>
If I understood your question correctly, this should be a solution:
const [oldOne, newOne] = array.reduce(
(acumm, current, index) => {
const [name, value] = current.split(':');
acumm[0].push(`${name}:`);
acumm[1].push(value ?? '');
return acumm;
},
[[], []]
);
Stackblitz Example
Info
// not mess up global vars, "Array" is a constructor
var Array = ["Alice:", "John:654", "Bob:123"];
** After Split **
var Array = ["Alice:", "John:", "Bob:"];
// not mess up with key words, "new" can only be called on
// constructors and array is as far i know not one
var new array = ["", "654", "123"];
Here's a solution using .map (so you don't need to keep track of the index)
var array = ["Alice:", "John:654", "Bob:123"];
var result = array.map(e => e.split(":")[1])
array = array.map(e => e.split(":")[0] + ":")
console.log(array, result)
Note that split(":")[1] will only give you the first entry if you have multiple ":" in the values, eg "John:654:999" - you can combine them with splice and join, eg:
parts.splice(1).join(":")
Here's the same solution, using a forEach if you prefer a single iteration over two:
var array = ["Alice:", "John:654:999", "Bob:123"];
var result = [];
var replacement = [];
array.forEach(e => {
var parts = e.split(":");
replacement.push(parts[0] + ":")
result.push(parts.splice(1).join(":"))
});
console.log(replacement, result)
I have a string:
var string = "test,test2";
That I turn into an array:
var array = string.split(",");
Then I wrap that array into a larger array:
var paragraphs = [array];
Which outputs:
[['test','test2']]
But I need it to output:
[['test'],['test2']]
Any clue how I can do this?
Just map each item into an array containing that item:
var string = "test,test2";
var result = string.split(",").map(x => [x]);
// ^--------------
console.log(result);
let test_string = "test,test2";
let result = test_string.split(',').map(item => [item])
console.log(result)
You can get expected result using array Concatenation.
var string = "test,test2";
var array = string.split(",");
var finalArray=[[array[0]]].concat([[array[1]]])
console.log(JSON.stringify(finalArray));
What version of JavaScript are you targeting?
This might be a general answer:
var arr = "test,test2".split(",");
var i = arr.length;
while(i--)
arr[i] = [arr[i]];
I need to remove the last element comma in Javascript array
var arr = ["AAA,","BBB,"];
I need the result below
var arr = ["AAA,","BBB"];
Any help is appreciated...
var arr = ["AAA,","BBB,"];
arr[arr.length - 1] = arr[arr.length - 1].replace(',', '');
console.log(arr);
Simply use with replace()
var arr = ["AAA,","BBB,"];
arr[arr.length-1] = arr[arr.length-1].replace(/\,/g,"");
console.log(arr)
One of the other way is this:
var arr = ["AAA,",",BBB,"];
arr.push(arr.pop().replace(/,$/, ''));
console.log(arr);
This answer explains how you can do it using regex:
>> var str = "BBB,"
>> str = str.replace(/,[^,]*$/ , "")
>> str
>> "BBB"
var arr = ["AAA,","BBB,"];
var lastelmnt = arr[(arr.length)-1].replace(',', '');
arr.splice(((arr.length)-1),1,lastelmnt);
Output :
["AAA,", "BBB"]
arr[arr.length-1] = arr[arr.length-1].slice(0,-1)
using JavaScript string split() method & Array splice() method.
DEMO
var arr = ["AAA,","BBB,"];
var arrLastElement = arr[arr.length-1];
var splitStr = arrLastElement.split(',');
var strWithoutComma = splitStr[0];
arr.splice(arr.length-1);
arr.push(strWithoutComma);
console.log(arr);
I want to convert the below array:
["A:100","B:234","C:124","D:634","E:543","F:657"];
Into:
["100:234:124:634:543:657"];
How to do this?
So not sure why you would want that particular output since it would just be a single item in an array but this should work:
var testArray = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var resultArray = [];
for(var i = 0; i < testArray.length; ++i) {
resultArray.push(testArray[i].split(':')[1]);
}
var strValue = resultArray.join(':');
console.log(strValue);
resultArray = [strValue];
console.log(resultArray);
You could iterate the array, return the number on the right and join it with ':'.
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"],
result = [data.map(function (a) {
return a.match(/\d*$/);
}).join(':')];
console.log(result);
Or a bit shorter
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"],
result = [data.map(RegExp.prototype.exec.bind(/\d*$/)).join(':')];
console.log(result);
<script>
var arr=["A:100","B:234","C:124","D:634","E:543","F:657"];
var str='';
for(var i=0;i<arr.length;i++){
str+=arr[i].split(":")[1]+":";
}
console.log(str.substring(0, str.length - 1));
</script>
You could just keep the number behind ":" and join new elements with ":"
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var results = [data.map(x => x.split(":")[1]).join(":")];
console.log(results);
You join it with what you want :, split it by what you don't won't /\D\:/ (non digit followed by :), and then join it using an empty string '':
var arr = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var result = [arr.join(':').split(/\D\:/).join('')];
console.log(result);
I have following JSON string :
{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}
I want location_id as
3,2
Simple:
var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var result = data.map(function(val) {
return val.location_id;
}).join(',');
console.log(result)
I assume you wanted a string, hence the .join(','), if you want an array simply remove that part.
You could add brackets to the string, parse the string (JSON.parse) and map (Array#map) the property and the join (Array#join) the result.
var string = '{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}',
array = JSON.parse('[' + string + ']'),
result = array.map(function (a) { return a.location_id; }).join();
console.log(result);
obj=[{"name":"Marine Lines","location_id":3}, {"name":"Ghatkopar","location_id":2}]
var res = [];
for (var x in obj)
if (obj.hasOwnProperty(x))
res.push(obj[x].location_id);
console.log(res.join(","));
var json = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var locationIds = [];
for(var object in json){
locationIds.push(json[object].location_id);
}
console.log(locationIds.join(","));
You can also look into .reduce and create a string manually
var d = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var location_id_str = d.reduce(function(p, c) {
return p ? p + ',' + c.location_id : c.location_id
},'');
console.log(location_id_str)
try this
var obj = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var output = obj.map( function(item){
return item.location_id;
});
console.log( output.join(",") )
var arr = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var location_array = [];
for( var i = 0; i < arr.length; i++ )
{
location_array.push( arr[i].location_id );
}//for
var location_string = location_array.join(",");
console.log(location_string);
Note: You may need to use JSON.parse() if the arr is in string format initially.
You can use for..of loop
var arr = [{
"name": "Marine Lines",
"location_id": 3
}, {
"name": "Ghatkopar",
"location_id": 2
}];
var res = [];
for ({location_id} of arr) {res.push(location_id)};
console.log(res);