I want to convert the below array - javascript

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

Related

How to put single quatation for values in javascript

I am trying to put value inside quatation in javascript but not working.I am getting datas values from service and i am trying to change the values with single quatation.I do not know how to do it.
Demo:https://stackblitz.com/edit/js-3tj28p?file=index.js
var datas="sd1,sd2,sd3,sd4";
output should be
console.log(datas)// 'sd1','sd2','sd3','sd4'
Please help..How to do it?
var datas="sd1,sd2,sd3,sd4";
var str = datas.split(",").map((item)=>{
return `'${item}'`;
}).join(",");
console.log(str);
var datas="sd1,sd2,sd3,sd4";
var str = datas.split(",").reduce((acc,cur,index) => {
if(index === datas.split(",").length-1){
return acc+=`'${cur}'`;
}
return acc+=`'${cur}',`;
},"");
console.log(str);
var datas="sd1,sd2,sd3,sd4";
var arr = datas.split(",");
var str = "";
for(let i = 0; i < arr.length; i++){
str+=`'${arr[i]}'`;
if(i !== arr.length-1) str+=`,`
};
console.log(str);
You split the datas string by , you will have ['sd1','sd2','sd3','sd4']
Map through each item and add '' to them, you will have ["'sd1'","'sd2'","'sd3'","'sd4'"]
Join them back, you will get 'sd1','sd2','sd3','sd4'
var datas="sd1,sd2,sd3,sd4";
let dataArr = datas.split(",")
dataArr = dataArr.map(item => `'${item}'`)
datas = dataArr.join()

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

Why is this returning an empty string?

I would like this to return s1 and s1 combined together, only the unique characters sorted in a new string called sortedString. Instead I get an empty string output.
ex input and output:
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
function longest(s1, s2) {
var sortedString = '';
var a = s1.split();
var b = s2.split();
for (i=0; i < a.length; i++) {
if (!sortedString.includes(a[i])) {
sortedString.concat(a[i]);
}
}
for (j=0; j < b.length; j++) {
if (!sortedString.includes(b[j])) {
sortedString.concat(b[j]);
}
}
return sortedString.sort();
}
In javascript String type is immutable and concat method don't mutate input so when you type:
sortedString.concat(b[j]);
sortedString is never muted. You should make this instead :
sortedString = sortedString.concat(b[j]);
You need to pass an empty string to split if you want to separate the string into a list of characters.
However, I would strongly recommend you solve this declaratively:
const allChars = s1.split('').concat(s2.split(''));
return allChars
.filter((char) => allChars.indexOf(char) === allChars.lastIndexOf(char))
.sort()
.join('');
var a = "xyaabbbccccdefww";
var b = "xxxxyyyyabklmopq";
var mySet = new Set(a.split("").concat(b.split("")));
var result = Array.from(mySet).sort().join("");
console.log(result);
With ES6, you could use Set with spread syntax ... for splitting the string and for populating an array.
var a = "xyaabbbccccdefww",
b = "xxxxyyyyabklmopq",
result = [...new Set([...(a + b)])].sort().join("");
console.log(result);

how to convert json values in comma separated string using javascript

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

Loop thru a string with numbers and symbols & push to array

I'm trying to loop thru a string with numbers that has a symbol inside, I want the numbers before the symbol to be pushed to an array then the symbol to another array and then get the rest of the numbers after the symbol pushed to a 3rd array.
var myString = "1234*5678";
var number1 = [];
for (i = 0; i < myString.length; i++) {
if (isNaN(myString[i]) === false) {
var firstSet = number1.push(myString[i]);
}
};
var mySymbol = [];
for (j = number1[0]; j < myString.length; j++) {
if (isNaN(myString[j]) === true) {
var mathematics = mySymbol.push(myString[j])
document.write(mySymbol[0])
}
};
when I document.write the "mySymbol" variable it gives the desired result, but when I call the "number1" variable it gives me the numbers from before and after the symbol I only want the numbers before the symbol to be pushed to the array, also how do I write the 3rd loop to get the numbers after the symbol pushed to a new array?
try
var arr=[[],[],[]]
index = 0
"1234*5678".split('').forEach(function(e){
if(parseInt(e)){
arr[index].push(e);
}else{
index ++;
arr[index++].push(e)
}
});
document.write('First Array ' +arr[0] + '<br>');
document.write('Secont Array ' +arr[1] + '<br>');
document.write('Third Array ' +arr[2]);
You could try using:
var myString = '1234*5678';
var resultArr = myString.match(/([a-zA-Z0-9]+)([^a-zA-Z0-9])([a-zA-Z0-9]+)/);
To get the string before symbol:
var myFirstSet = resultArr[1];
To get symbol:
var mySymbol = resultArr[2];
To get the string after symbol:
var mySecondSet = resultArr[3];
To convert each of these three groups into their own arrays:
var result = [];
resultArr
.slice(1)
.forEach(
function(s){
result.push(s
.split('')
.map(
function(n){
return parseInt(n) || n;
}
)
)
}
);
The following code accomplishes the goal:
var str = '1234*5678';
var arr = str.match(/([a-zA-Z0-9]+)|\*/g);
console.log(arr[0], arr[1], arr[2]);
http://jsfiddle.net/hp2ohvzb/

Categories