Need to split string based on given numeric value in jquery - javascript

I have a string like this, Fy 2002.car.state.
I need to split this based on value, if the value is 0 I need split like "Fy 2002","car","state" separately.If the value is 1, I need split like this "Fy 2002.car","state".
How do I achieve this without using for loop? Thanks.

First create the array using split.
Then cut off the array using splice.
Finally join the cut items using join and put it into array.
function mysplit(str, index){
var a = str.split('.')
if(index){
a[0] += '.' + a.splice(1, index).join('.')
}
return a
}
Other possibility is to use a reduce function.
function mysplit2(str, index){
var a = str.split('.')
if(index){
a = a.reduce(function(p, c, i) {
p.push(c)
return (i <= index ? [p.join('.')] : p)
},[])
}
return a
}

My interpretation of the question
split the string
join the first nth elements with .
var str = "Fy 2002.car.state",
a = str.split('.');
function split(a, index) {
if (index) {
a[0] += '.' + a.splice(1, index).join('.');
}
document.write('<pre>' + index + ' ' + JSON.stringify(a, 0, 4) + '</pre>');
}
split(a.slice(0), 0);
split(a.slice(0), 1);
split(a.slice(0), 2);

You can do it with split
var str="Fy 2002.car.state";
var result= str.split('.');
Fiddle Here

Related

Double for loop in Javascript inner array length

I am trying to create a function that takes in a string and changes each letters value to a "(" if the character is not duplicated in the string, and a ")" if the character does have a duplicate present in the string. I have decided to go an unconventional route to solve this problem but I am running in to an issue with a double for loop. From what I understand, the inner for loop in javascript does not have access to the variables outside of the loop. I want to loop through every item in an array twice but I'm not sure what to set the inner loops length as.
Here is my code:
function sortAndChange(word) {
const splitter = word.toLowerCase().split("");
//let jSplitter = word.toLowerCase().split("").length;
let endResult = "";
let truthArray = [];
for(i = 0; i < splitter.length; i++){
for(j = 0; j < splitter.length; j++){
console.log(j);
if(splitter[i] == splitter[j]){
truthArray.push(true);
} else {
truthArray.push(false);
}
}
console.log(truthArray);
truthArray.every(item => item === false) ? endResult += "(" : endResult += ")";
truthArray = [];
}
console.log(endResult);
}
Expected Result:
sortAndChange("Success") //expected output: ")())())"
sortAndChange("easy") //expected output: "(((("
You can do that in following steps:
Convert string to array using split and use map() on it.
Compare the indexOf() and lastIndexOf() to check if its duplicate or not.
Return the ) or ( based on ur condition. And then at last join the array
function sortAndChange(str){
let arr = str.toLowerCase().split('')
return arr.map(x => {
//if its not duplicated
if(arr.indexOf(x) === arr.lastIndexOf(x)){
return '('
}
//If its duplicated
else{
return ')'
}
}).join('');
}
console.log(sortAndChange("Success")) //expected output: ")())())"
console.log(sortAndChange("easy")) //expected output: "(((("
You could take a object and keep a boolean value for later mapping the values.
This approach has two loops with O(2n)
function sortAndChange(word) {
word = word.toLowerCase();
var map = [...word].reduce((m, c) => (m[c] = c in m, m), {});
return Array
.from(word, c => '()'[+map[c]])
.join('');
}
console.log(sortAndChange("Success")); // )())())
console.log(sortAndChange("easy")); // ((((
This can easily be achieved using a combination of regex and the map construct in javascript:
const input = "this is a test";
const characters = input.toLowerCase().split('');
const transformed = characters.map(currentCharacter => {
const regexpression = new RegExp(currentCharacter, "g");
if (input.toLowerCase().match(regexpression || []).length > 1) return ')'
return '(';
}).join("");
console.log(transformed);
Look at the following snippet and comments
function sortAndChange(str) {
// we create an array containing the characters on the string
// so we can use Array.reduce
return str.split('').reduce((tmp, x, xi) => {
// we look if the character is duplicate in the string
// by looking for instance of the character
if (str.slice(xi + 1).includes(x.toLowerCase())) {
// Duplicate - we replace every occurence of the character
tmp = tmp.replace(new RegExp(x, 'gi'), ')');
} else {
// Not duplicate
tmp = tmp.replace(new RegExp(x, 'gi'), '(');
}
return tmp;
}, str);
}
console.log(sortAndChange('Success')); //expected output: ")())())"
console.log(sortAndChange('Easy')); //expected output: "(((("
1) use Array.from to convert to array of chars
2) use reduce to build object with key-value pairs as char in string and ( or ) as value based on repetition .
3) Now convert original string to result string using the chars from above object.
function sortAndChange(str) {
const str_arr = Array.from(str.toLowerCase());
const obj = str_arr.reduce(
(acc, char) => ((acc[char] = char in acc ? ")" : "("), acc),
{}
);
return str_arr.reduce((acc, char) => `${acc}${obj[char]}`, "");
}
console.log(sortAndChange("Success")); // ")())())"
console.log(sortAndChange("easy")); // ((((

Javascript array remove odd commas

I need to create a string like this to make works the mapserver request:
filterobj = "POLYGON((507343.9 182730.8, 507560.2 182725.19999999998, 507568.60000000003 182541.1, 507307.5 182563.5, 507343.9 182730.8))";
Where the numbers are map coordinates x y of a polygon, the problem is with Javascript and OpenLayer what I have back is an array of numbers, How can I remove just the ODD commas (first, third, fifth...)?
At the moment I've created the string in this way:
filterobj = "POLYGON((" +
Dsource.getFeatures()[0].getGeometry().getCoordinates() + " ))";
And the result is:
POLYGON((507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8));
It's almost what I need but, I need to remove the ODD commas from the Dsource.getFeatures()[0].getGeometry().getCoordinates() array to make the request work, how can I do that?
The format that you need is WKT, and OpenLayers comes with a class that allows you to parse its geometries as WKT easily, as below:
var wktFormatter = new ol.format.WKT();
var formatted = wktFormatter.writeFeature(Dsource.getFeatures()[0]);
console.log(formatted); // POLYGON((1189894.0370893013 -2887048.988883849,3851097.783993299...
Look at code snippet :
Help method : setCharAt ,
Take all commas ,
take all odds commas with i % 2 == 0
// I need to start from somewhere
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var POLYGON = [507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8];
var REZ = "";
REZ = POLYGON.toString();
var all_comma = [];
for(var i=0; i<REZ.length;i++) {
if (REZ[i] === ",") all_comma.push(i);
}
for(var i=0; i<all_comma.length;i++) {
if (i % 2 == 0 ) {
REZ = setCharAt(REZ,all_comma[i],' ');
}
}
console.log(REZ);
// let return nee element intro POLYGON
// reset
POLYGON = REZ.split(',');
console.log(POLYGON);
What about this:
const str = Dsource.getFeatures()[0].getGeometry().getCoordinates()
// str = "1,2,3,4,5,6"
str.split(',').map((v, i) => {
return (i % 2) ? v : v + ','
}).join(' ')
// "1, 2 3, 4 5, 6"
There are a couple of ways to go, both involve getting rid of whitespace first. The first matches coordinate pairs, removes the comma, then pastes them back together.
The second splits into individual numbers, then formats them with reduce. Both should be ECMA-262 ed5 (2011) compatible but I don't have an old enough browser to test them.
var s = '507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8';
var re = /\d+\.?\d*,\d+\.?\d*/g;
// Solution 1
var x = s.replace(/\s/g,'').match(re).map(function(x){return x.replace(',',' ')}).join();
console.log(x);
// Solution 2
var t = s.replace(/\s/g,'').split(',').reduce(function (acc, v, i) {
i%2? (acc[acc.length - 1] += ' ' + v) : acc.push(v);
return acc;
}, []).join(',');
console.log(t);
One approach would be using Array.reduce():
var input = '1.0, 2.0, 3.0, 4.0, 5.0, 6.0';
var output = input
.split(',')
.reduce((arr, num, idx) => {
arr.push(idx % 2 ? arr.pop() + ' ' + num : num);
return arr;
}, [])
.join(',');
// output = '1.0 2.0, 3.0 4.0, 5.0 6.0'

Remove duplicate lines with position delimiter

I need a function javascript.
I have a list with format
abc|a|1
abc|a|2
abcd|a|1
abc|b|1
And i want to duplicate by first and second postion (split "|")
New list is:
abc|a|1
abcd|a|1
abc|b|1
Thank you so much
You could filter the data with Array#filter() and take a temporary object for lookup if there is already an item with the same two parts in the result.
var list = ['abc|a|1', 'abc|a|2', 'abcd|a|1', 'abc|b|1'],
result = list.filter(function (a) {
var b = a.split('|'),
k = b[0] + '|' + b[1];
if (!this[k]) {
this[k] = true;
return true;
}
}, {});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Formatting a JS array into specific string

I have a Javascript array
var arr = ['[dim].[att].&[123]','[dim].[att5].&[123]','[dim4].[att].&[123]','[dim3].[att].&[123]','[dim].[att].&[222]']
from this array I need to produce output like this:
var str = " 'dim'[att] = 123 || 'dim'[att] = 222 , 'dim'[att5] = 123 , 'dim4'[att] = 123 , 'dim3'[att] = 123 ";.
I first need to split each value in the array by .& and then I need to group all the items by index 0 of the resultant array. So in this case I will group [dim].[att].&[123] & [dim].[att].&[222] becuase of [dim].[att]
From each of these items, now I need to split by ]. and produce requires output such that [dim].[att].&[123] becomes 'dim'[att] = 123
I do not want to use multiple for loops for this purpose. I already have that solution ready. So far i am able to group the items, but not sure how to generate required output. Check this fiddle for my solution
You just need to use Array.map and Array.join
var str = arr.map(function(s){
var a = s.match(/\w+/g);
return "'" + a[0] + "'[" + a[1] + "] = " + a[2];
}).join("||");
In the above, we are taking the three parts which we want into an Array using s.match(/\w+/g) and then returning in the format we want.
Also, at last, Array.join is called with || as the String
DEMO
I was looking for this; Code below and DEMO
var arr = ['[dim].[att].&[123]', '[dim].[att5].&[123]', '[dim4].[att].&[123]', '[dim3].[att].&[123]', '[dim].[att].&[222]']
var res = _.chain(arr)
.groupBy(function (x) {
return x.match(/.+?\.&/i)[0];
})
.map(function(y) {
return _.map(y, function (z) {
var a = z.match(/\w+/g);
return "'" + a[0] + "'[" + a[1] + "] = " + a[2];
}).join(" || ");
})
.value().join(", ");
console.log(res)

Count occurrence times of each character in string

I have a string like this:
(apple,apple,orange,banana,strawberry,strawberry,strawberry). I want to count the number of occurrences for each of the characters, e.g. banana (1) apple(2) and strawberry(3). how can I do this?
The closest i could find was something like, which i dont know how to adapt for my needs:
function countOcurrences(str, value){
var regExp = new RegExp(value, "gi");
return str.match(regExp) ? str.match(regExp).length : 0;
}
Here is the easiest way to achieve that by using arrays.. without any expressions or stuff. Code is fairly simple and self explanatory along with comments:
var str = "apple,apple,orange,banana,strawberry,strawberry,strawberry";
var arr = str.split(','); //getting the array of all fruits
var counts = {}; //this array will contain count of each element at it's specific position, counts['apples']
arr.forEach(function(x) { counts[x] = (counts[x] || 0)+1; }); //checking and addition logic.. e.g. counts['apples']+1
alert("Apples: " + counts['apple']);
alert("Oranges: " + counts['orange']);
alert("Banana: " + counts['banana']);
alert("Strawberry: " + counts['strawberry']);
See the DEMO here
You can try
var wordCounts = str.split(",").reduce(function(result, word){
result[word] = (result[word] || 0) + 1;
return result;
}, {});
wordCounts will be a hash {"apple":2, "orange":1, ...}
You can print it as the format you like.
See the DEMO http://repl.it/YCO/10
You can use split also:
function getCount(str,d) {
return str.split(d).length - 1;
}
getCount("fat math cat", "at"); // return 3

Categories

Resources