I hava a string like this "sum 123,645,423,123,432";
How can i convert this string to be like this:
{
“sum”: [ 123,645,423,123,432 ]
}
I try it like this:
var arr = "sum 123,645,423,123,432";
var c = arr.split(',');
console.log(c);
VM3060:1 (5) ["sum 123", "645", "423", "123", "432"]
Thanks!
First, i .split() the string by whitespace, that returns me an array like this ["sum" , "123,645,423,123,432"]
Instead of writing var name = str.split(" ")[0] and var arrString = str.split(" ")[1] i used an destructuring assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Next step is to split the arrString up by , and then .map() over each element and convert it to an number with Number().
Finally i assign an object to result with a dynamic key [name] and set arr to the dynamic property.
var str = "sum 123,645,423,123,432";
var [name,arrString] = str.split(" ");
var arr = arrString.split(",").map(Number);
let result = {
[name]: arr
}
console.log(result);
//reverse
var [keyname] = Object.keys(result);
var strngArr = arr.join(",");
var str = `${keyname} ${strngArr}`
console.log(str);
const str = "sum 123,645,423,123,432";
const splittedString = str.split(" ");
const key = splittedString[0];
const values = splittedString[1].split(",").map(Number);
const myObject = {
[key]: [...values]
};
console.log(myObject);
There are many ways to dot that,one way to do it using String.prototype.split()
let str = "sum 123,645,423,123,432";
let split_str = str.split(' ');
let expected = {};
expected[split_str[0]] = split_str[1].split(',');
console.log(expected);
This solution is equivalent to #Yohan Dahmani with the use of destructuring array for more legible code.
const str = "sum 123,645,423,123,432";
const [key,numbersStr] = str.split(' ');
const numbersArr = numbersStr.split(',').map(n => parseInt(n, 10));
const result = {[key]: numbersArr};
console.log(result);
Related
I have a string say
var str = "xy,yz,zx,ab,bc,cd";
and I want to split it on the 2nd last occurrence of comma i.e
a = "xy,yz,zx,ab"
b = "bc,cd"
How can I achieve this result?
You can do that by mixing few methods, just like that:
const str = "xy,yz,zx,ab,bc,cd";
const tempArr = str.split(',');
const a = tempArr.slice(0, -2).join(',');
const b = tempArr.slice(-2).join(',');
console.log("a:", a, "b:", b);
Or you can use regex:
var str = "xy,yz,zx,ab,bc,cd";
const [a, b] = str.split(/,(?=[^,]*,[^,]*$)/);
console.log(a);
console.log(b);
Using a regex
var str= "xy,yz,zx,ab,bc,cd"
const parts = [,a,b]=str.match(/(.*),(.*,.*)$/)
console.log(a,b)
counting from back:
let str = "xy,yz,zx,ab,bc,cd";
let idx = str.lastIndexOf(',' , str.lastIndexOf(',')-1);
str.slice(0, idx);
str.slice(idx + 1);
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
//Finished result should be:
result == ["10000.", "9409.", "13924.", "11025.", "10000.", "_.", "11025.", "13225.", "_.", "9801.", "12321.", "12321.", "11664."]
After each "." I want to split it and push it into an array.
You split it, and map over. With every iteration you add an . to the end
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let result = stringToSplit.split(".").map(el => el + ".");
console.log(result)
You could match the parts, instead of using split.
var string = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.",
result = string.match(/[^.]+\./g);
console.log(result);
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
var arr = stringToSplit.split(".").map(item => item+".");
console.log(arr);
split the string using . delimiter and then slice to remove the last empty space. Then use map to return the required array of elements
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let newData = stringToSplit.split('.');
let val = newData.slice(0, newData.length - 1).map(item => `${item}.`)
console.log(val)
you could use a lookbehind with .split
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let out = stringToSplit.split(/(?<=\.)/);
console.log(out)
I am trying to get text from an array except year,month,date using javascript.I do not know how do it.
var arr = [
"power-still-rate-19.08.22",
"main-still-rate-19.08.22",
"oil-power-rate-19.08.22",
"oil-mill-rate-19.7.2"
];
var result;
for (var i = 0; i < arr.length; i++) {
result = arr[i].remove('?????????');
}
console.log(result);
//result should be like = power-still-rate,main-still-rate,oil-power-rate ;
Split, slice and join
var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.map(item => item.split("-").slice(0,-1).join("-"))
console.log(result);
Split, pop and join
var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.map(item => { let res = item.split("-"); res.pop(); return res.join("-") })
console.log(result);
No map:
var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.join("").split(/-\d{1,}\.\d{1,}\.\d{1,}/);
result.pop(); // last empty item, not needed if you do not want an array just join with comma
console.log(result);
Use a regular expression to match non-digit characters from the start of the string, followed by - and a digit:
const input = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
const output = input.map(str => str.match(/\D+(?=-\d)/)[0]);
console.log(output);
Using split on - ,splicing the last element which is the date and joining on -
var arr=["power-still-rate-19.08.22","main-still-rate-19.08.22","oil-power-rate-19.08.22"];
arr.forEach(function(e,i){
arr[i]=e.split('-').splice(0,3).join('-')
})
console.log(arr)
You can remove back string by using slice function and join them with join function.
var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.map(str => str.slice(0, str.lastIndexOf('-'))).join(',');
console.log(result);
You can use String#replace method to remove certain pattern from string using RegExp.
const input = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
const res = input.map(str => str.replace(/-\d{1,2}\.\d{1,2}\.\d{1,2}$/, ''));
console.log(res);
I am new in javascript. I want to replace string value from array if array key value match with string value
Here is my following code:
var arr= [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
var string = "11-12";
My Output will be :
var str ="XYZ-ABC";
Use String#replace method with a callback.
var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
var string = "11 - 12";
// match all digits in string and replace it with
// corresponding value in `arr`
var res = string.replace(/\d+/g, function(m) {
return arr[m];
})
console.log(res);
You can use regx.test() to get the Boolean value to check if it is character or not .
var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
if(/[a-zA-Z\s]+/.test(arr[11])&&/[a-zA-Z\s]+/.test(arr[12])){
var str=arr[11]+ " " +arr[12];
}
You just need array methods (split map and join), neither regex nor jquery:
var str = string.split("-").map(elem => arr[elem]).join("-");
I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method