JavaScript: Insert a character after every N characters - javascript

I have a string, which always has a lenght of 32:
var str = "34v188d9cefa401f988563fb153xy04b";
Now I need to add a minus (-) after following number of characters:
First minus after 8th character
Second minus after 12th character
Third minus after 16th character
Fourth minus after 20th character
Output should be:
34v188d9-cefa-401f-9885-63fb153xy04b
So far I have tried different calculations with e.g.:
str.split('').reduce((a, b, c) => a + b + (c % 6 === 4 ? '-' : ''), '');
But I don't get the expected result.

You could use a regex replacement:
var str = "34v188d9cefa401f988563fb153xy04b";
var output = str.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
console.log(output);

If you want to use reduce you can do something like this
var str = "34v188d9cefa401f988563fb153xy04b";
const result = str.split('').reduce((res, c, i) => {
const hiphensPositions = [7, 11, 15, 19]
return res + c + (hiphensPositions.includes(i)?'-':'')
}, '')
console.log(result)

var str = "34v188d9cefa401f988563fb153xy04b";
var a=""
for (let i in str){if (i == 7 || i==11 || i==15 || i ==
19){a = a+str[i]+"-"} else{a+=str[i] }}
should do it.

You can splice them.
const str = "34v188d9cefa401f988563fb153xy04b";
const indices = [8,12,16,20]
let strArr = str.split('')
indices.reverse().forEach(i => strArr.splice(i,0,'-'))
console.log(strArr.join(''))

You can use the substring method
var str = '34v188d9cefa401f988563fb153xy04b';
var newStr =
str.substring(0, 8) +
'-' +
str.substring(8, 12) +
'-' +
str.substring(12, 16) +
'-' +
str.substring(16, 20) +
'-' +
str.substring(20);
console.log(newStr);

I have a for loop algorithm for this case. It take O(n) complexity. The code example is like this:
const str = "34v188d9cefa401f988563fb153xy04b"
let dashPosition = [8, 12, 16, 20]
for(i=arr.length-1 ; i>=0 ; i--) {
str = str.substr(0, [arr[i]]) + '-' + str.substr(arr[i])
}
Is the answer match what you want?

You can do this with splice and a loop.
The loop iterates all the positions you want to add a -, and uses the index to ensure that each time you add a new character to the string, the required positionto insert the - is also incremented.
const str = "34v188d9cefa401f988563fb153xy04b";
const positions = [8, 12, 16, 20];
const strChars = str.split("");
for(const [index, position] of positions.entries()) {
strChars.splice(position + index, 0, "-");
}
const output = strChars.join("");
console.log(output); // expected output: "34v188d9-cefa-401f-9885-63fb153xy04b"
You could wrap this up in a function that just takes the string and positions array like so:
function insertHyphens(str, positions) {
const strChars = str.split("");
for(const [index, position] of positions.entries()) {
strChars.splice(position + index, 0, "-");
}
return strChars.join("");
}
console.log(insertHyphens("34v188d9cefa401f988563fb153xy04b", [8, 12, 16, 20]));
// expected output: "34v188d9-cefa-401f-9885-63fb153xy04b"

Related

Using join method dynamically

I have a reference array based on each English alphabet index:
let reference = [0, 2, 3];
and an array of words or even phrases:
let words = ["A", "C", "D"];
And I want to join each word from words array to create a simple sentence but considering the gaps between words ( whenever the values in the reference array aren't consecutive numbers! ), so the desired output would be :
A...C D // gaps filled with three dots
The problem is I can't find a solution to use join() method to do it!
Any help would be appreciated
You can create a new array from words based on the gaps in reference and then join:
let reference = [0, 2, 3];
let words = ["A", "C", "D"];
let res = [];
reference.forEach((n, i) => {
if (n - reference[i - 1] >= 2) res.push('...', words[i]);
else res.push(words[i]);
});
console.log(res.join(' '));
You could reduce the array by checking the delta of the last value and the actual value.
var reference = [0, 2, 3],
result = reference.reduce((r, v, i, { [i - 1]: last }) =>
r + (r && (i && v - last > 1 ? '...' : ' ')) + (v + 10).toString(36).toUpperCase(), '');
console.log(result);
An approach of comparing reference array values each time while iterating on the actual words array:
let reference = [0, 2, 3, 4, 7];
let words = ["A", "C", "D", "E", "H"];
let prev = 0;
let joined = words[prev];
for (let i = 1, l = words.length; i < l; ++i) {
const diff = reference[i] - reference[prev];
if (diff > 1) {
joined += "..." + words[i];
} else {
joined += " " + words[i];
}
prev = i;
}
//Since CDE ar continuous and AC and EH are not
console.info(joined);

Returning new array with ascii values and numbers of previous array

I'm writing a function without the use of any JS built-in functions. This function accepts an array ['z','C',2,115,30] and then creates a new array with ascii values of chars in that first array plus the normal numbers that were there previously, so: [127, 67, 2, 115,30]. The problem I'm having is that I cannot properly get the numbers from the 1st array into the second array.
So far I can get the new array to [127,67,2,1,1,5,3,0]. So the chars ascii value is being inputted into the new array properly, but while iterating through the numbers it puts each digit of a number and then a comma into the array when i just want the whole number to be inputted instead of each digit.
function func(x){
var str = '';
var arr = [];
for(var i=0; i<x.length;i++){
str += x[i]
}
for(var j=0; j<str.length;j++){
if(isNaN(str[j])){
arr += str.charCodeAt(j) + ', ';
}
else if(!isNaN(str[j])){
arr += str[j] + ', ';
}
} print(arr)
}
func(['z','C',2,115,30])
I expect output of [122, 67, 2, 115, 30], current output is [122, 67, 2, 1, 1, 5, 3, 0,]
Don't combine into one string - instead, use a simple for loop:
function func(x) {
var arr = [];
for (let i = 0; i < x.length; i++) {
if (typeof x[i] == "string") arr[arr.length] = (x[i].charCodeAt(0);
else arr[arr.length] = x[i];
}
console.log(arr);
}
func(['z','C',2,115,30]);
Using array methods is much simpler though:
function func(x) {
var arr = x.map(e => typeof e == "string" ? e.charCodeAt(0) : e);
console.log(arr);
}
func(['z','C',2,115,30]);

How to join array elements in pairs in javascript

I have a array of numbers [1,2,3,4,5,6,7,8,9,10] and I want to make it into a string like this: '1,2 3,4 5,6 7,8 9,10'. Is there some fast and simple vay to do this in javascript or do i have to use the loop?
for(let i = 0; i < array.length; i++){
if(i%2 == 0){
res += array[i] + ',';
} else {
res += array[i] + ' ';
}
}
You can use reduce to get the result you desire:
[1,2,3,4,5,6,7,8,9,10]
.reduce((acc, val, idx) =>
idx % 2 === 0
? (acc ? `${acc} ${val}` : `${val}`)
: `${acc},${val}`, '')
// "1,2 3,4 5,6 7,8 9,10"
By taking advantage of the third parameter of the reduce function we know the index of the element we are currently iterating over, therefore also making this function work for arrays that aren't numbers 1 through 10.
You could get pairs with comma and then join the array with spaces for the string, but you need still a loop
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
temp = [],
i = 0,
string;
while (i < array.length) {
temp.push(array.slice(i, i += 2).join());
}
string = temp.join(' ');
console.log(string);
You could chunk the array, and join the elements with commas and spaces:
var arr = [1,2,3,4,5,6,7,8,9,10,11]
chunkArr = arr.reduce((acc, item, index) => {
const i = Math.floor(index/2)
if(!acc[i]) {
acc[i] = []
}
acc[i].push(item)
return acc
}, [])
arr = chunkArr.map(arr => arr.join(',')).join(' ')
console.log(arr)
Note, this code works with an odd amount of numbers too.

JavaScript: Count instances of specific integers in a string

OKAY, so I have a bunch of numbers in a div, lets say something like...
<div id="countme">7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8</div>
And I want to use JavaScript to return...
The specific number, and
The number of times that number occurred in the div
Example Output: "(2,0),(1,2),(3,3),(2,5),(1,6),(1,7),(1,8)"
Explained: Zero appears two times, two appears one time, three appears three times, etc...
I've tried the following...
var str = document.getElementById('countme').innerText;
var match = str.match(/7/g);
var match1 = str.match(/5/g);
alert(match.length);
alert(match1.length);
But I need it to display the number it searched for, and I need everything to be in one alert.
Any thoughts?
Thanks! :)
JSBIN: https://jsbin.com/tesezoz/1/edit?js,console
var str = "7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8";
// first get the numbers
var m = str.split(', ').map(Number);
// turn it into an object with counts for each number:
var c = m.reduce(function(a, b) {
a[b] = ++a[b] || 1;
return a;
}, {});
// now you have an object that you can check for the count
// which you can alert... its the c variable
Try this...
var str = "7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8";
str = str.replace(/\s/g, "");
str = str.split(",");
var result = {};
str.forEach(function(value) {
if (result[value]) {
result[value]++;
}
else {
result[value] = 1;
}
});
var output = "";
for(value in result) {
output += (output == "" ? "" : ",") + "(" + value + "," + result[value] +")";
}
alert(output);
It splits the string and removes any whitespace, so you're left with an array (and no assumption that the delimiter is consistent).
It then creates an object representing each value and the count.
It finally converts that into an output, similar to the one in your example.
Here is the Answer
var str = document.getElementById('countme').innerText;
var array = JSON.parse("[" + str+ "]");
var counts = {};
array.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts);
I think this is almost as efficient as you can get. It also serves as a general count unique matches method:
var testString = document.getElementById('countme').innerText;
count = {};
var regX = /(\d+)/g;
var res;
while (res = regX.exec(testString )) {
count[res[0]] = (count[res[0]] !== undefined ? ++count[res[0]] : 1)
};

Sum of a number's digits with JavaScript

I have:
var nums = [333, 444, 555];
I want to treat each digit in a number as a separate number and add them together. In this case sums should be:
9 = 3 + 3 + 3
12 = 4 + 4 + 4
15 = 5 + 5 + 5
How to achieve this using JavaScript?
you can use a simple modulo operation and dividing
var a = [111, 222, 333];
a.forEach(function(entry) {
var sum = 0;
while(entry > 0)
{
sum += entry%10;
entry = Math.floor(entry/10);
}
alert(sum)
});
Here’s a different approach that converts the numbers to strings and converts those into an array of characters, then the characters back into numbers, then uses reduce to add the digits together.
var nums = [333, 444, 555];
var digitSums = nums.map(function(a) {
return Array.prototype.slice.call(a.toString()).map(Number).reduce(function(b, c) {
return b + c;
});
});
digitSums; // [9, 12, 15]
If your array consists of bigger numbers (that would overflow or turn to Infinity), you can use strings in your array and optionally remove the .toString().
Now in our days, with the advantages of ES6, you can simply spread each value of your array inside map, and the with reduce make the operation:
var numbers = [333, 444, 555];
const addDigits = nums => nums.map(
num => [...num.toString()].reduce((acc, act) => acc + parseInt(act), 0)
);
console.log(addDigits(numbers));
var nums = [333, 444, 555];
nums.map(number => [...String(number)].reduce((acc, num) => +num+acc , 0));
//output [9, 12, 15]
Unary plus operator (+num) is converting string into integer.
If you want to generate an array consisting of the sum of each digit, you can combine the .map()/.reduce() methods. The .map() method will create a new array based on the returned value (which is generated on each iteration of the initial array).
On each iteration, convert the number to a string (num.toString()), and then use the .split() method to generate an array of numbers. In other words, 333 would return [3, 3, 3]. Then use the .reduce() method to add the current/previous numbers in order to calculate the sum of the values.
var input = [333, 444, 555];
var sumOfDigits = input.map(function(num) {
return num.toString().split('').reduce(function(prev, current) {
return parseInt(prev, 10) + parseInt(current, 10);
}, 0);
});
//Display results:
document.querySelector('pre').textContent =
'Input: ' + JSON.stringify(input, null, 4)
+ '\n\nOutput: ' + JSON.stringify(sumOfDigits, null, 4);
<pre></pre>

Categories