How to remove character from last array element - javascript

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);

Related

How to push a group of arrays (string format) to an array?

I am getting a group of array from database in this format [52,16,135],[54,16,140],[22,16,140] and I need to push all elements of of it into new array separately but looks like my code adding them as an array to the code
but what I need is
[
"True",
"52",
"16",
"135",
"54",
"16",
"140",
"22",
"16",
"140",
"Other Value"
]
var str = '[52,16,135],[54,16,140],[22,16,140]';
var arr =[];
arr.push('True');
arr.push(str.replace(/\[/g, "").replace(/\]/g, "").split(','));
arr.push('Other Value');
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var str = '[52,16,135],[54,16,140],[22,16,140]';
var arr =[];
arr.push('True');
arr.push(str.replace(/\[/g, "").replace(/\]/g, "").split(','));
arr.push('Other Value');
An easy fix to your code will be using the spread syntax inside the Array.push() method to spread all the elements of the array generated by split() as arguments of the push() method. Also, you can use one replace() sentence replace(/[[\]]/g, "") in replacement of the two you have.
var str = '[52,16,135],[54,16,140],[22,16,140]';
var arr =[];
arr.push('True');
arr.push(...str.replace(/[[\]]/g, "").split(','));
arr.push('Other Value');
console.log(arr);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Just add .flat() method to your result. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatenter code here
var str = '[52,16,135],[54,16,140],[22,16,140]';
var arr =[];
arr.push('True');
arr.push(str.replace(/\[/g, "").replace(/\]/g, "").split(','));
arr.push('Other Value');
console.log(arr.flat());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You're almost there. Just instead of pushing, concatenate.
var str = '[52,16,135],[54,16,140],[22,16,140]';
var innerArr = str.replace(/\[/g, "").replace(/\]/g, "").split(',');
var arr = ["True"].concat(innerArr).concat(["Other Value"]);
console.log(arr);
Instead of using replace, you could add a [] around the string to create a valid JSON of 2D array. Then parse the string and use flat.
var str = '[52,16,135],[54,16,140],[22,16,140]';
const newArray = JSON.parse(`[${str}]`).flat();
console.log(newArray)
ES5 solution if flat and template literals aren't supported in your browser:
var str = '[52,16,135],[54,16,140],[22,16,140]';
var parsed = JSON.parse('[' + str + ']'),
newArray = [].concat.apply([], parsed);
console.log(newArray)
Well, you have 2 immediate options I can think of:
First option: ES6 spread syntax
const str = '[52,16,135],[54,16,140],[22,16,140]';
const strArr = str.replace(/\[/g, "").replace(/\]/g, "").split(',');
const arr = ['True', ...strArr, 'Other Value'];
console.log(arr);
Second option: Array.prototype.concat()
const str = '[52,16,135],[54,16,140],[22,16,140]';
const strArr = str.replace(/\[/g, "").replace(/\]/g, "").split(',');
let arr = [];
arr.push('True');
arr = arr.concat(strArr);
arr.push('Other Value');
console.log(arr);
I would go with option 1 if that's possible for you.
Cheers :)
try
['True', ...str.match(/\d+/g), 'Other Value'];
var str = '[52,16,135],[54,16,140],[22,16,140]';
var arr = ['True',...str.match(/\d+/g),'Other Value'];
console.log(arr);

String Split for only first time

I want to split the below input string as output string.
Input = 'ABC1:ABC2:ABC3:ABC4'
Output = ['ABC1','ABC2:ABC3:ABC4']
let a = 'ABC1:ABC2:ABC3:ABC4'
a.split(':', 2); // not working returning ['ABC1','ABC2']
You can use this, works in all browsers
var nString = 'ABC1:ABC2:ABC3:ABC4';
var result = nString.split(/:(.+)/).slice(0,-1);
console.log(result);
let a = 'ABC1:ABC2:ABC3:ABC4'
const head = a.split(':', 1);
const tail = a.split(':').splice(1);
const result = head.concat(tail.join(':'));
console.log(result); // ==> ["ABC1", "ABC2:ABC3:ABC4"]
Example: https://jsfiddle.net/4nq1tLye/
You can use indexOf and slice:
var a = 'ABC1:ABC2:ABC3:ABC4';
var indexToSplit = a.indexOf(':');
var first = a.slice(0, indexToSplit);
var second = a.slice(indexToSplit + 1);
console.log(first);
console.log(second);
console.log('ABC1:ABC2:ABC3:ABC4'.replace(':','#').split('#'));

Javascript string to special array

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 want to convert the below array

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);

Regex for creating an array from String

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]);

Categories