Related
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);
});
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
Hi I am exporting data to csv file using javascript. I need to sort the data according to specific column index.
Code:
$.each(exportArray, function (index, value) {
csvData.push(x[index] + "," + y[index] + "," + d[index] + "," + z[index] + ","+ a[index] + "," + e[index] + "," + b[index] + "," + c[index]);
});
csvData.sort();
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(output);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
E.g.: csvData.sort() is sorting data acoording to first column as default. I want to have it sorted according to the third column i.e.. by d[index].
I tried this csvData.sort(sort_by(d[index])); and it is not working.
I have one more issue . Since I am exporting the data to csv. Now in d[index] from the server if I have three values like d[index]="cat,dog,bat" . It is getting displayed in 3 adjacent columns. I want it in the same column. Can I change the delimiter to something else from comma.
Code:
csvData.push(x[index] + "," + y[index] + "," + d[index] + "," + z[index] + ","+ a[index] + "," + e[index] + "," + b[index] + "," + c[index]);
You need to sort the data before you write it to the CSV. This is more easily done if the data is in an array of objects instead of spread out in one array per property. To achive this you can either just put the data in objects when it is created or read, or you can convert it with a snippet like this:
var count = x.length;
var objects = new Array(count);
for(i=0; i++; i<count) {
objects[i] = {
x: x[i],
y: y[i],
d: d[i],
z: z[i],
a: a[i],
e: e[i],
b: b[i],
c: c[i],
};
}
Then you can easily sort the data, for example by the x property, with this code:
function compare(a, b) {
if (a.x < b.x) return -1;
if (a.x > b.x) return 1;
return 0;
}
objects.sort(compare);
Then you will get the arrays sorted, and can access individual properties with for instance objects[i].x.
You have to write a custom compare function
// The following function is used to sort on the basis of the third element
function compareByThird(a, b) {
var aArr = a.split(',');
var bArr = b.split(',');
return aArr[2] - bArr[2];
}
csvData.sort(compareByThird);
It works if the third column is a numeric value.
If not (for example for strings) it necessary to use the following code:
// The following function is used to sort on the basis of the third element
function compareByThird(a, b) {
var aArr = a.split(',');
var bArr = b.split(',');
if (aArr[2] < bArr[2]) {
return -1;
} else if (aArr[2] > bArr[2] {
return 1;
} else {
return 0;
}
}
I am writing javascript to try to do only a few simple tasks.
var series = ["A","0","0","B","0","C","0","0","D","0"];
var off = 1;
var built = 1;
var position = 1;
var masterSeries = [];
var slot = 1;
console.log(series);
function createMaster() {
for (var i = 0; i <= series.length - 1; ++i) {
masterSeries[i] = ["Mode" + off];
//console.log("Creating Internal Array #" + off);
off++
}
off = 1;
//since we already have first series we just assign it here
masterSeries[0] = series;
return masterSeries;
}
function buildAltSeriesNoNull() {
for (var i = 1; i <= series.length - 1; i++) {
slot++;
console.log("Checking Slot: " + slot);
if (series[i] != "0") {
console.log("Found Non Null, building: " + built);
//code to mutate the original array into new arrays goes here
var temp = series;
var back = temp.slice(i, series.length);
var front = temp.slice(0,i);
var newline = back.concat(front);
masterSeries[position] = newline;
position++;
console.log("Added to Master Series Mini Array:" + position);
built++;
} else {
console.log("Skipping Slot: " + slot);
}
off++;
//masterSeries[i] = ["Love" + numOffset]; //set the mode
}
console.log(masterSeries);
}
console.log(createMaster()); //Create the MasterSeries Display the Banks
console.log("Memory banks have been created, and we have a valid series of numbers to work with!");
console.log('\n');
console.log(buildAltSeriesNoNull());
I have an hard coded array of 10 index's that hold possible letters
there will be a random amount of letters populating the 10 slots, it should not matter if the first index is null or not null
For Example
A00B0C00D0
ABC00D00EF
0A0B0C0D0E
The zero's should be treated as null (will come in handy in a second)
First I want the program to iterate through each index after the first and
A. determine if it is a null or a valid letter
B. If it is null, then skip to next index
C. If it has a valid letter than it will create a new array and 'resort' the original array into a custom sorted array that looks like this. (using one of the example original arrays above)
ORIGINAL ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->A00B0C00D0
Program checks index 2, and it is null, move to next, checks index 3 it is null, move to next. Index 4 has a value, "B" So now program creates a new array simply called array2nditerate and the array now looks like this
SECOND ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->B0C00D0A00
THIRD ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->C00D0A00B0
FOURTH ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->D0A00B0C00
So it is creating a new array for each unique letter based on the position in the original array it sat.
So once It creates all the unique sorted arrays for each slot that had a value. I would then need it to do the entire same process but this time to the positions in the original array that had null values only...so for example it would look like this.
ORIGINAL ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->A00B0C00D0
FIRST NULL ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->00B0C00D0A
SECOND NULL ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->0B0C00D0A0
THIRD NULL ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->0C00D0A00B
FOURTH NULL ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->00D0A00B0C
FIFTH NULL ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->0D0A00B0C0
SIXTH NULL ARRAY
index-->[0,1,2,3,4,5,6,7,8,9]
Value-->0A00B0C00D
If you notice it created 4 Non Null Arrays custom sorted because there were only 4 letters in the array of 10 possible index positions. it created six non nulls because 10 positions -4 non null arrays is 6 null arrays
I am not sure as to which method is quicker, better. Iterating with one for loop and sorting out into a pile of null arrays and sorting into a pile of non null arrays, or writing two separate functions that iterate
once through looking only for non null index's and sorting that way
sorting through looking for null index's and sorting that way
This is based on the thought of maintaining the original array and works only with two abstraction, the offset of the found letters and zeros.
I think, a simple iteration should sort out zero and letter indices.
this.array.forEach(function (a, i) {
a === '0' ? that.indexZero.push(i) : that.indexLetter.push(i);
});
Working example:
function ClassWithoutName(data) {
var that = this;
this.array = data.split(''),
this.indexLetter = [],
this.indexZero = [];
this.array.forEach(function (a, i) {
a === '0' ? that.indexZero.push(i) : that.indexLetter.push(i);
});
}
ClassWithoutName.prototype = {
constructor: ClassWithoutName,
getItem: function (index) {
return this.array[index % this.array.length];
},
getArray: function (offset) {
offset = offset || 0;
return this.array.map(function (_, i, o) {
return o[(i + offset) % o.length];
});
}
};
var instanceWithoutName = new ClassWithoutName('A00B0C00D0');
console.log('data: ' + instanceWithoutName.getArray().join(''));
console.log('letters:');
instanceWithoutName.indexLetter.forEach(function (a, i) {
console.log(i + ': offset: ' + a + ' ' + instanceWithoutName.getArray(a).join(''));
});
console.log('zeros:');
instanceWithoutName.indexZero.forEach(function (a, i) {
console.log(i + ': offset: ' + a + ' ' + instanceWithoutName.getArray(a).join(''));
});
console.log('special selected item, here 2nd abstraction of letter element 3:');
console.log(instanceWithoutName.getItem(instanceWithoutName.indexLetter[2] + 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
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)