How to quickly generate an array from strings in Javascript [duplicate] - javascript

This question already has answers here:
Create an array of characters from specified range
(13 answers)
Closed 3 years ago.
In ruby I can use the following code to generate an array of strings from a to z:
alphabet = ('a'..'z').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
Is there a similar function call in Javascript?

Unfortunately, ECMAScript does not have a Range in its standard library. However, what you can do, is to use the Array.from factory function to construct an Array using a mapping function.
Something like this:
const alphabet = Array.from({ length: 26 }, (_, i) => i + 97).map(String.fromCharCode);
Or, without magic numbers:
const charCodeOfA = "a".charCodeAt(0), //=> 97
charCodeOfZ = "z".charCodeAt(0), //=> 122
lengthOfAlphabet = charCodeOfZ - charCodeOfA + 1, //=> 26
alphabet = Array.from({ length: lengthOfAlphabet }, (_, i) => i + charCodeOfA).
map(String.fromCharCode);
In future versions of ECMAScript, it would be nice to use do expressions to avoid polluting the namespace with those temporary helper variables:
const alphabet = do {
const charCodeOfA = "a".charCodeAt(0), //=> 97
charCodeOfZ = "z".charCodeAt(0), //=> 122
lengthOfAlphabet = charCodeOfZ - charCodeOfA + 1; //=> 26
Array.from({ length: lengthOfAlphabet }, (_, i) => i + charCodeOfA).
map(String.fromCharCode)
}

The easy way to do that is
var alphabet =[];
for(var i = "a".charCodeAt(0); i <= "z".charCodeAt(0); i++) {
alphabet.push(String.fromCharCode(i))
}

Related

How can I move items from an array from one position to another? [duplicate]

This question already has answers here:
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed last month.
const elementeSelected = ["a", "b"];
const allElements = ["m", "s", "e", "r", "q", "d", "a", "b", "c"];
// result allElements = ["a", "b", "m", "s", "e", "r", "q", "d", "c"];
https://codesandbox.io/s/distracted-lederberg-yji13f?file=/src/index.js:0-175
I tried to reorder the items form allElement. I want the items from elementeSelected to be move from their position in allElements to the first position.
You need to concat the arrays together and remove the ones that were already used. You can do that with spread syntax and with filter. The filter uses includes to check if it is duplicated.
const elementeSelected = ["a", "b"];
const allElements = ["m", "s", "e", "r", "q", "d", "a", "b", "c"];
const result = [...elementeSelected, ...allElements.filter(n => !elementeSelected.includes(n))];
console.log(result);
var allelements = ["m", "s", "e", "r", "q", "d", "a", "b", "c"];
var x= 6;
var pos=0;
var temp=allelements[x];
var i;
for (i=x; i>=pos; i--)
{
allelements[i]=allelements[i-1];
}
allelements[pos]=temp;
var y= 7;
var pos2=1
<!-- begin snippet: js hide: false console: true babel: false -->
var temp2=allelements[y];
var i;
for (i=y; i>=pos2; i--)
{
allelements[i]=allelements[i-1];
}
alllements[pos2]=temp2;
console.log(allelements);

Converting nested loops into forEach();

Im trying to learn forEach() method but i cant find more advanced examples. So i thought about refactoring my Codewars code to learn from it. I dont know know to properly use forEach method in nested loops. Hope You can help me learn from this example :)
6 kyu - Replace With Alphabet Position
https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript
function alphabetPosition(text) {
let textToArray = text.replace(/[^a-zA-Z]/gi,'').toUpperCase().split(''); //Eliminate anything thats not a letter
const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
let pointsHolder = []; //empty array for score
for (let i = 0; i < textToArray.length; i++){
for (let j = 0; j < alphabet.length; j++) {
if (textToArray[i] == alphabet[j] ) { //We check the index of given string letter in alphabet
pointsHolder.push(j+1) //give it a score based on place in alphabet(+1 for 0 as 1st index)
}
}
}
return pointsHolder.join(' '); //return scored array as a string with spaces
}
There is really no need to use a nested loop, which is computationally expensive. With that, you also don't have to manually create an A-Z array.
You can easily convert alphabets to any arbitrary number using String.charCodeAt(). a has a character code of 97, b has a character code of 98, and etc... to get a one-based index (a=1, b=2, ...) you jus t need to subtract 96 from the number.
function alphabetPosition(text) {
const alphabets = text.toLowerCase().replace(/[^a-z]/g, '').split('');
return alphabets.map(alphabet => alphabet.charCodeAt(0) - 96).join(' ');
}
Alternatively you can also use a for...of loop, but that requires storing the array in yet another variable before returning it:
function alphabetPosition(text) {
const alphabets = text.toLowerCase().replace(/[^a-z]/g, '');
const codes = [];
for (const alphabet of alphabets) {
codes.push(alphabet.charCodeAt() - 96);
}
return codes.join(' ');
}
(Note: #Terry's solution is still the more efficient solution to your code challenge)
You can replace it in the following way:
function alphabetPosition(text) {
let textToArray = text.replace(/[^a-zA-Z]/gi, '').toUpperCase().split('');
const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
let pointsHolder = [];
textToArray.forEach(t2a => {
alphabet.forEach((a, j) => {
if (t2a == a) { pointsHolder.push(j + 1) }
})
})
return pointsHolder.join(' ');
}
console.log(alphabetPosition("ABCSTU"))
An alternative to the charCode solution proposed in Terry's answer but which also avoids nested loops is be to create a Map of the characters you want to score against and then access it per character from the passed string.
Keep in mind that strings are iterable without needing to convert to an array.
function alphabetPosition(text) {
text = text.toUpperCase().replace(/[^A-Z]/gi, '');
const alphabet = new Map(
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
.map((v, i) => [v, i + 1])
);
const pointsHolder = [];
for (const char of text) {
pointsHolder.push(alphabet.get(char))
}
return pointsHolder.join(' ');
}
console.log(alphabetPosition("AB😬CS🐹TU"))
This also allows you to use a Map which doesn't necessarily have consecutive charCodes
function alphabetPosition(text) {
text = text.toUpperCase().replace(/[^😬🐹🤓]/gi, '');
const alphabet = new Map(
["😬", "🐹", "🤓"]
.map((v, i) => [v, i + 1])
);
const pointsHolder = [];
for (const char of text) {
pointsHolder.push(alphabet.get(char))
}
return pointsHolder.join(' ');
}
console.log(alphabetPosition("AB😬CS🐹TU"))

how do i return a spliced array using multiple indexes from a different array

dft=["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"];
ans=[4, 6, 12, -1];
for(x=0;x<ans-1;x++){
dft.splice(ans[x],0,"-");}
return dft;
I am trying to return an array that has "-" placed into the dft array using the indexes in the ans array except the -1 index.
result im getting is ["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"]
this is the codepen i am working on
Firstly, it's not doing anything because your for loop end condition should be checking the loop parameter x against the length of the ans array, i.e. x < ans.length -1. Secondly, since splice is changing the array, your ans indices will be incorrect after you insert the first hyphen, so you should do it in reverse order like so:
dft = ["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"];
ans = [4, 6, 12, -1];
for (x = ans.length - 2; x >= 0; x--) {
dft.splice(ans[x], 0, "-");
}
console.log(dft);
We start at the end of the array, which would be ans.length - 1, except you want to skip the last element, so we start at ans.length - 2. Remember though that this assumes that the last element should be ignored.
You can reach your desired result with Array#reduce.
let dft = ["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"];
let ans = [4, 6, 12, -1];
let res = dft.reduce((s,a,i) => {
(ans.indexOf(i) > -1) ? s.push(a, '-') : s.push(a);
return s;
}, []);
console.log(res);
Arrays do not have a numeric primitive, so you want your for loop condition to read x < ans.length.
Your index also needs to be ans[x] + x, because each splice() is increasing the length of the array by 1.
These changes alone should accomplish your stated goal. However I would also add:
you should be declaring variables purposefully, rather than using implicit globals.
you can replace your for loop using the forEach() method, which can make your intention more clear.
you probably want spacing around terms and operators, which also helps readability.
You need to sort the index array and do in the reverse order otherwise it would change the index of other elements.
var dft = ["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"],
ans = [4, 6, 12, -1];
// sor the array to place - at the last higher index first
ans.sort(function(a, b) {
return a - b;
});
// get array length
var x = ans.length;
// iterate upto index reach to 0 or reaching to -1
while (x-- && ans[x] > -1) {
dft.splice(ans[x], 0, "-");
}
console.log(dft);
Just for completeness, a solution with Array#reduceRight
var array = ["t", "h", "i", "s", "I", "s", "S", "p", "i", "n", "a", "l", "T", "a", "p"],
indices = [4, 6, 12, -1],
result = indices.reduceRight((r, i) => (~i && r.splice(i, 0, '-'), r), array);
console.log(result.join(''));

manually sorting a paragraph by made-up alphabet with javascript

I'm trying to sort a paragraph alphabetically, not according to the normal ABC but a made-up one (var order).
I wrote this function and it works great, but only for the first letter of each word - not in-word sorting as well (for example, in correct ABC 'banana' would come before 'birthday').
I'm not sure where to go from here.
$("#send").click(function () {
var text = $("#text").val().replace(/[^A-Za-z0-9_\s]/g, "").toUpperCase().split(" ");
var order = ["Q", "B", "K", "D", "H", "V", "Z", "E", "F", "O", "G", "L", "M", "S", "N", "P", "I", "X", "A", "R", "W", "U", "C", "J", "T", "Y"];
var i, t, j;
var newText = []; // will hold the new alphabet
// function to sort the words:
for (i = 0; i < order.length; i++) {
for (t = 0; t < text.length; t++) {
var firstChar = text[t][0];
if (order[i] == firstChar) {
newText.push(text[t]);
}
}
}
console.log(newText.join(','));
});
EDIT:
An example input can be: "Hi dan don't you think that this is awesome",
and I want the output to be: "don't dan hi is awesome this think that you".
You could use an object with the index of the letters and use Array#sort with a callback which looks for every letter adn calculates the order.
function foo(text) {
var text = text.replace(/[^A-Za-z0-9_\s]/g, "").toUpperCase().split(" "),
order = "QBKDHVZEFOGLMSNPIXARWUCJTY",
ref = {};
order.split('').forEach(function (a, i) { ref[a] = i + 1; });
text.sort(function (a, b) {
var i = 0, v;
do {
v = (ref[a[i]] || 0) - (ref[b[i]] || 0);
i++;
} while (!v)
return v;
});
console.log(text.join(', '));
}
foo('a aa ab b ba bb');
foo('banana birthday');
The problem with your algorithm is that it only compares the first letter in each word, but if the letters are the same the algorithm needs to compare the next letter in each word. Here's a solution that uses recursion:
function doSort(inputArr) {
var words = inputArr.slice(0);
var alphabet = ["Q", "B", "K", "D", "H", "V", "Z", "E", "F", "O", "G", "L", "M", "S", "N", "P", "I", "X", "A", "R", "W", "U", "C", "J", "T", "Y"];
words.sort(function(item1, item2) {
return sortRecursive(item1, item2, 0);
});
function sortRecursive(item1, item2, idx) {
if (item1.length <= idx && item2.length <= idx) {
return 0;
} else if (item1.length <= idx) {
return -1;
} else if (item2.length <= idx) {
return 1;
} else if (item1[idx] == item2[idx]) {
return sortRecursive(item1, item2, idx+1);
} else {
return alphabet.indexOf(item1[idx].toUpperCase()) - alphabet.indexOf(item2[idx].toUpperCase());
}
}
return words;
}
var arr = ["banana", "quebec", "bird", "birthday", "birdman", "bird"];
var sortedArr = doSort(arr);
console.log('unsorted',arr);
console.log('sorted', sortedArr);
https://jsfiddle.net/2qgaaozo/

Google Spreadsheets Script Keeps Writing Empty Strings

I have a Google form that gets submitted to a Google spreadsheet. On the spreadsheet side, I have a Google Apps Script that is supposed to encrypt the submitted password. But for whatever reason, it writes an empty string to where the encrypted password should be. This is really starting to stress my out. Here is my code:
function encryptPassword(e) {
var password = e.values[6];
var split = password.split("");
password = "";
var char;
for(char in split) {
password = password.concat(getBinary(split[char]));
}
var spreadsheet = SpreadsheetApp.openById("1CywforbyBmPDHt2Uw9lJtyhqeklAAJp0IG7GfVV6U5U");
spreadsheet.getRange("G" + spreadsheet.getLastRow().toString()).setValue(password);
spreadsheet.getRange("H" + spreadsheet.getLastRow().toString()).setValue(password);
}
function getBinary(char) {
var binary = "";
var numValue;
var range;
var value;
var chars = [
["#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"],
["#", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
["&", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"],
["%", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
["$", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
];
for(range in chars) {
for(value in range) {
if(value > 0) {
if(char == chars[range][value]) {
numValue = value - 1;
binary = binary + chars[range][0];
if(numValue / 8 >= 1) {
numValue = numValue - 8;
binary = binary.concat("1");
} else {
binary = binary.concat("0");
}
if(numValue / 4 >= 1) {
numValue = numValue - 4;
binary = binary.concat("1");
} else {
binary = binary.concat("0");
}
if(numValue / 2 >= 1) {
numValue = numValue - 2;
binary = binary.concat("1");
} else {
binary = binary.concat("0");
}
if(numValue / 1 >= 1) {
binary = binary.concat("1");
} else {
binary = binary.concat("0");
}
}
}
}
}
return binary;
}
The encryptPassword(e) function is set to run whenever a form is submitted to the spreadsheet. Also please be aware that I have modified the contents of the chars array in an attempt to keep my encryption private. This shouldn't make a difference though since the rest of the code stays the same.
How do I fix my script so it actually writes an encrypted password to the spreadsheet rather than an empty string?
You've got two For/In loops:
for(range in chars) {
for(value in range) {
A For/In loop is meant to loop through the properties of an object. When you use it to loop through an array, like you are doing, the "property" is the index number of the array.
So the line:
for(range in chars) {
Is causing the variable range to be a number value on every loop. On the first loop, the value of range is zero.
The second loop:
for(value in range) {
is never looping. There is nothing to loop through. The value of the variable range is just a single number. You can't loop through a single number. If you use the debugger, you can watch what every line is doing, and execute one line of code at a time.
If you want to get the index position of one of the characters in the password, you could use indexOf(). For example, if the character in the password was the letter "i".
var indexPosition = chars[2].indexOf(char);
The value of indexPosition would be 9. The third array in the outer array chars has an element "i" in the 9th index position.

Categories

Resources