I have an array say var arr = [1,2,3,4,5,6,7,8]
Now I do a join like give below
arr.join("|");
My requirement is that this array should contain new line after each third element. Like
1|2|3
4|5|6
7|8|9
A help will be appreciated.
Thanks
arr.join("|").replace(/([^|]+?\|[^|]+?\|[^|]+?)\|/g, "$1\n");
One possible approach:
i.join('|').replace(/\|/g, function(){
var c = 0;
return function(str) {
return ++c % 3 ? str : '\n';
}
}());
replace essentially replaces each third | in the string with \n.
You should slice your array into multiple sub arrays which can individually be joined together:
var arr = [1,2,3,4,5,6,7,8,9];
// temporary array to push sliced and joined sub array into
var arr_ = [], i;
for (i = 0; i < arr.length; i = i + 3) {
// slice range of 3 element from arr, join and push into arr_
arr_.push(arr.slice(i, i + 3).join("|"));
}
// join by newline
arr_.join("\n");
You can extract 3 asvariable to vary the column width.
If you have array of digits:
arr.join("|").match(/(\d+\|\d+\|\d+)/g).join("\n");
Related
edit: without giving me too much of the answer to how i can do it in a for loop. Could you give me the logic/pseudocode on how to achieve this? the one part i am stuck at is, ok i know that i have to take the first index number and add array.length-1 zeros to it (2 zeros), but i am confused as to when it arrives at the last index, do i put in a if statement in the for loop?
In the below example 459 would be put in an array [4,5,9]
Now I want to take 4 add two zeros to the end because it has two numbers after it in the array
Then I want to take 5 and add one zero to it because there is one number after it in the array.
then 9 would have no zeros added to it because there are no numbers after it.
So final output would be 400,50,9
how can i best achieve this?
var num=459;
var nexint=num.toString().split("");
var finalint=nexint.map(Number);
var nextarr=[];
You need to use string's repeat method.
var num=459;
var a = (""+num).split('').map((c,i,a)=>c+"0".repeat(a.length-i-1))
console.log(a);
Here's another possible solution using a loop.
var num = 459;
var a = ("" + num).split('');
var ar = [];
for (var i = 0; i < a.length; i++) {
var str = a[i];
str += "0".repeat(a.length-i-1);
ar.push(str);
}
console.log(ar);
You could use Array#reduce and Array#map for the values multiplied by 10 and return a new array.
var num = 459,
result = [...num.toString()].reduce((r, a) => r.map(v => 10 * v).concat(+a), []);
console.log(result);
OP asked for a solution using loops in a comment above. Here's one approach with loops:
var num = 459
var numArray = num.toString().split('');
var position = numArray.length - 1;
var finalArray = [];
var i;
var j;
for(i = 0; i < numArray.length; i++) {
finalArray.push(numArray[i]);
for(j = 0; j < position; j++) {
finalArray.push(0);
}
position--;
}
console.log(finalArray);
The general flow
Loop over the original array, and on each pass:
Push the element to the final array
Then push X number of zeros to the final array. X is determined by
the element's position in the original array, so if the original
array has 3 elements, the first element should get 2 zeros after it.
This means X is the original array's length - 1 on the first pass.
Adjust the variable that's tracking the number of zeros to add before
making the next pass in the loop.
This is similar to #OccamsRazor's implementation, but with a slightly different API, and laid out for easier readability:
const toParts = n => String(n)
.split('')
.map((d, i, a) => d.padEnd(a.length - i, '0'))
.map(Number)
console.log(toParts(459))
I am trying to find a better way to get an array of strings based on a string by separating on a special character, in my case the / character.
So given the following input:
"/bob/ross/is/awesome/squirrels"
I would like to end up with:
[
"/bob/ross/is/awesome/squirrels",
"/bob/ross/is/awesome",
"/bob/ross/is",
"/bob/ross",
"/bob"
]
I must admit that despite my years of experience I am stuck as to how to approach this eloquently and succinctly.
Here is my current code:
getWords = function( string ){
// Get an array of all words in the provided string separating on "/"
let words = string.split("/");
// Filter out empty strings from leading/trailing "/" characters
words = words.filter( function(a){return a !== ""} );
// Create an array to store results in
let results = [];
// Create an iteration for each word in the array
for (var i=0, j=words.length; i<j; i++){
// Create a string to concatenate to
let result = "";
// Loop over each word in the array minus the current iteration of "i"
for (var k=0, l=words.length - i; k<l; k++){
// Contatenate using the special character plus the current word
result += "/" + words[k];
}
// Push the resulting string to the results array
results.push(result);
}
// Return the results array
return results;
}
And a code snippet for you to check what's going on:
getWords = function( string ){
// Get an array of all words in the provided string separating on "/"
let words = string.split("/");
// Filter out empty strings from leading/trailing "/" characters
words = words.filter( function(a){return a !== ""} );
// Create an array to store results in
let results = [];
// Create an iteration for each word in the array
for (var i=0, j=words.length; i<j; i++){
// Create a string to concatenate to
let result = "";
// Loop over each word in the array minus the current iteration of "i"
for (var k=0, l=words.length - i; k<l; k++){
// Contatenate using the special character plus the current word
result += "/" + words[k];
}
// Push the resulting string to the results array
results.push(result);
}
// Set the results to display
resultsDisplay.innerHTML = results.toString().replace(/,/g, " -- ");
// Return the results array
return results;
}
input = document.getElementsByTagName("input")[0];
resultsDisplay = document.getElementsByClassName("results")[0];
input.addEventListener("input", function(){
getWords(input.value)
});
getWords(input.value);
<input value="bob/ross/is/awesome/squirrels" />
<p class="results"></p>
You may do as follows;
var str = "/bob/ross/is/awesome/squirrels",
res = s => s.length ? [s].concat(res(s.match(/.*(?=\/.+$)/)[0])) : [];
console.log(res(str));
Explanation: So in the above snippet we have a String.match() portion with regexp which matches the text before the last "/" character. This matched text will be the next string we will feed to the res function call recursively from within itself like res(s.match(/.*(?=\/.+$)/)[0]).
So the res function is a recursive one with a terminating condition being an argument s of 0 length string in which case it returns an empty array. However if s is not empty then it's first placed in an array and then the array is concatenated with the result of a recursive call and returned.
This would do it:
var path = "/bob/ross/is/awesome/squirrels";
var arr = path.split('/').filter(val => val);
var res = arr.map((val, idx) => '/'+arr.slice(0,idx+1).join('/'))
console.log(res)
Here's another approach:
let str = "/bob/ross/is/awesome/squirrels";
let re = /\/+[^\/]+/g;
let result = [];
while (re.exec(str)) {
result.push(str.substr(0, re.lastIndex));
}
result.reverse();
console.log(result);
So i have this string
first €999, second €111
Im trying to make an array that looks like this (numbers after every €)
999,111
Edit:
Yes i have tried to split it but wont work. i tried to look it up on google and found something with indexof but that only returned the number of the last €.
rowData[2].split('€').map(Number);
parseInt(rowData[2].replace(/[^0-9\.]/g, ''), 10);
split(rowData[2].indexOf("€") + 1);
The numbers are variable.
var input ="first €999, second €111";
var output=[];
var arr = input.split(",");
for(var i=0;i<arr.length;i++)
{
output.push(parseInt(arr[i]));
}
var output_string = output.stingify();
console.log(output); //Output Array
console.log(output_string); //Output String
If the numbers will always be of 3 digits in length, you can do this. If not, you need to specify a bit more.
var string = "€999, second €111";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].substring(temp[i].indexOf("€"),3));
}
//digitArray now contains [999,111];
Edit, based on your requirement of variable digit lengths
var string = "€999, second €111, third €32342";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].replace(/^\D+/g, '')); //Replace all non digits with empty.
}
//digitArray now contains [999,111,32342]
friends.
I have an array and it contains some string values.
ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array".
if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
You could do it using each() and charAt:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});
HI ,
In Java Script ,
var a ="apple-orange-mango"
var b ="grapes-cheery-apple"
var c = a + b // Merging with 2 variable
var c should have value is "apple-orange-mango-grapes-cheery" .Duplicated should be removed.
Thanks ,
Chells
After your string is combined, you will want to split it using the delimiters (you can add these back in later).
example:
var a ="apple-orange-mango"
var b ="grapes-cheery-apple"
var c = a + "-" + b
var Splitted = c.split("-");
the Splitted variable now contains an array such as [apples,orange,mango,grapes,cherry,apple]
you can then use one of many duplicate removing algorithms to remove the duplicates. Then you can simply do this to add your delimiters back in:
result = Splitted.join("-");
Here's a brute force algorithm:
var a;
var b; // inputs
var words = split(a+b);
var map = {};
var output;
for( index in words ) {
if( map[ words[index] ]!=undefined ) continue;
map[ words[index] ] = true;
output += (words[index] + '-');
}
output[output.length-1]=' '; // remove the last '-'
The map acts as a hashtable.
Thats it!
I don't know if it is an homework.
By the way you can split strings like a and b with the split method of string object.
in your case:
firstArray=a.split("-");
secondArray=b.split("-");
the removal of duplicates is up to you...
In your simple example, just use var c = a + "-" + b;
If you want duplicates removed, split a and b into arrays, and combine them, like so:
var avalues = a.split("-");
var bvalues = b.split("-");
var combined = avalues.concat( bvalues );
// now loop over combined and remove duplicates