Formatting a JS array into specific string - javascript

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)

Related

Search a string for words in array

Not seeing the error in my ways...
I am trying to search a string with keywords from an array and I just keep coming up with no results, please help me see what I am doing wrong here.
var stringArray = ["Trans", "Diode", "Label"];
var str = "Label, SpotChem Pipettes Oversticker";
var a = (stringArray.indexOf(str) > -1);
var b = (str.indexOf(stringArray) > -1);
console.log("a: " + a + " b: " + b);
//even using jquery: $.inArray(str, stringArray) returns -1
...
If needed you can see this code in a FIDDLE
You need to compare each word of the array to the string in question. You can use Array.some
var containsKeyWords = stringArray.some(word => str.indexOf(word) > -1);

Dynamically change element name in jquery

The following is my element id and I want to update it dynamically.
invoice[46][ap_details][4][ap_header_id]
I want to update only second number, i.e. [4], like this:
invoice[46][ap_details][5][ap_header_id]
I am using below code which is updating both the values.
var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
strName = strName.replace(/[\[\]']+/g, '');
var intNumber = parseInt(strName) + 1;
return '[' + intNumber + ']';
});
Any help would be appreciated.
var strName = "invoice[46][ap_details][4][ap_header_id]";
var parts = strName.split('[');
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
var strNewName = parts.join('[');
console.log(strNewName);
If you don't want to use arrow functions replace this line:
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
with this:
parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });
Explanation:
split will return an array like this:
[
"invoice",
"46]", // parts[1] to change this
"ap_details]",
"4]", // parts[3] to change this (and so on, you do the math)
"ap_header_id]"
]
The /^\d+/ will match any number at the begining (no need for the g modifier).
Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41".
Then after you change what you want, join the parts using join with the same character you used for splitting ([).
Using this regex /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi you can construct the string back and change your integer.
var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];
Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/
Maybe dont use regex to build your element id. You can do its as follows as well:
var id = 5
var name = "invoice[46][ap_details][";
name += id;
name += "][ap_header_id]";
var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]"
var replaced = toReplace.replace(/~~id~~/g, id);
console.log(name);
console.log(replaced);

Print the number of values as take from the Index value from array

Recently Attended the interview, Some one asked the question like below:
var array = [0,1,2,3,4,5];
Output :
temp:
temp1:1
temp22:22
temp333:333
temp4444:4444
temp55555:55555
I tried below code it is working fine but is there any best solution for this example :
array.forEach(function(item,index){
var text ="";
if(index >= 2){
for(var j =1; j <= index; j++){
text += index;
}
console.log("temp"+text + ":" + text);
}else{
console.log("temp"+index + ":" + index);
}
});
Thanks in advance!
Using ES6 template strings and String.prototype.repeat
var array = [0,1,2,3,4,5];
array.forEach(item => {
const text = String(item).repeat(item);
console.log(`temp${text}: ${text}`);
})
And the same code translated into ES5 - this will work in all browsers starting from IE9 and above.
var array = [0,1,2,3,4,5];
array.forEach(function(item) {
var text = Array(item+1).join(item);
console.log("temp" + text + ": " + text);
})
Since String.prototype.repeat does not exist in ES5, there is a bit of a hack to generate a string of specific length with repeating characters:
Array(initialCapacity) will create a new array with empty slots equal to what number you pass in, Array.prototype.join can then be used to concatenate all members of the array into a string. The parameter .join takes is the separator you want, so, for example you can do something like this
var joinedArray = ["a","b","c"].join(" | ");
console.log(joinedArray);
However, in this case, each of the members of the array is blank, since the array only has blank slots. So, upon joining, you will get a blank string, unless you specify a separator. You can leverage that to get a repeat functionality, as you are essentially doing something like this
//these produce the same result
var repeatedA = ["","",""].join("a");
var repeatedB = Array(3).join("b");
console.log("'a' repeated:", repeatedA);
console.log("'b' repeated:", repeatedB);
Using the Array function, you can scale it to any number of repeats you want. The only trick is that you need to add 1 when creating the array, since you get one less character when joining.
You could iterate the array and iterate the count. Then display the new string.
var array = [0, 1, 2, 3, 4, 5];
array.forEach(function (a, i) {
var s = '';
while (i--) {
s += a;
}
console.log ('temp' + s + ':' + s);
});

Need to split string based on given numeric value in jquery

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

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