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"))
Related
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))
}
I'm trying to push to an initially empty array with the condition that the content at two different indexes of two different non-empty arrays don't have the same character and the initially empty array has not already pushed that character earlier
I've tried using the not operator, contains, includes, but nothing seems to work.
var pushToArray = [];
for (var i = 0; i < 5; i++) {
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not in 'pushToArray'
if (characters[i] != moreCharacters[randomIndex] && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
if(arrayContent1("I") == arrayContent2("I")) then don't push
Sample expected results for pushToArray:
["F", "R", "E", "D", "L"]
Sample actual results for pushToArray:
["I", "F", "R", "D", "Y"] I don't want that letter 'I' in there
The test
if (characters[i] != moreCharacters[randomIndex]
will fail only if characters[i] is the picked character - it sounds like you want to make sure that none of the characters match the picked character:
if (!characters.includes(moreCharacters[randomIndex])
If you're only conditionally pushing to the array, then change the for loop to
while (pushToArray.length < 5) {
var pushToArray = [];
while (pushToArray.length < 5) {
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not already in there
if (!characters.includes(moreCharacters[randomIndex]) && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
}
console.log(pushToArray);
But, the logic would be easier to follow if you filtered the characters out of moreCharacters beforehand:
const excludeChars = ["M", "U", "S", "I", "C"];
const inputChars = ["F", "R", "I", "E", "N", "D", "L", "Y"]
.filter(char => !excludeChars.includes(char));
const result = [];
for (let i = 0; i < 6; i++) {
const randIndex = Math.floor(Math.random() * inputChars.length);
const [char] = inputChars.splice(randIndex, 1);
result.push(char);
}
console.log(result);
This code does this:
I would like array3 to only have letters from array2 that are not in array1. I basically don't want any letters that exist in array1
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
var pushToArray = [];
var i, l = characters.length;
for (i = 0; i < l; i++) {
randomIndex = Math.floor(Math.random() * moreCharacters.length);
// && push to 'pushToArray' if the character is not in 'pushToArray'
if (!characters.includes(moreCharacters[randomIndex]) && !pushToArray.includes(moreCharacters[randomIndex])) {
pushToArray.push(moreCharacters[randomIndex]);
}
}
console.log(pushToArray);
This can be simply achieved by doing:
var characters = ["M", "U", "S", "I", "C"];
var moreCharacters = ["F", "R", "I", "E", "N", "D", "L", "Y"];
var pushedToArray = [...characters].filter(x => moreCharacters.indexOf(x) === -1);
var finalArray = pushedToArray.filter((item, index) => pushedToArray.indexOf(item) === index);
I have JS array with strings, for example:
var strArray = [ "q", "w", "w", "e", "i", "u", "r"];
I need to compare for duplicate strings inside array, and if duplicate string exists, there should be alert box pointing to that string.
I was trying to compare it with for loop, but I don't know how to write code so that array checks its own strings for duplicates, without already pre-determined string to compare.
The findDuplicates function (below) compares index of all items in array with index of first occurrence of same item. If indexes are not same returns it as duplicate.
let strArray = [ "q", "w", "w", "w", "e", "i", "u", "r"];
let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)
console.log(findDuplicates(strArray)) // All duplicates
console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates
Using ES6 features
Because each value in the Set has to be unique, the value equality will be checked.
function checkIfDuplicateExists(arr) {
return new Set(arr).size !== arr.length
}
var arr = ["a", "a", "b", "c"];
var arr1 = ["a", "b", "c"];
console.log(checkIfDuplicateExists(arr)); // true
console.log(checkIfDuplicateExists(arr1)); // false
var strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
var alreadySeen = {};
strArray.forEach(function(str) {
if (alreadySeen[str])
console.log(str);
else
alreadySeen[str] = true;
});
I added another duplicate in there from your original just to show it would find a non-consecutive duplicate.
Updated version with arrow function:
const strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
const alreadySeen = {};
strArray.forEach(str => alreadySeen[str] ? console.log(str) : alreadySeen[str] = true);
You could take a Set and filter to the values that have already been seen.
var array = ["q", "w", "w", "e", "i", "u", "r"],
seen = array.filter((s => v => s.has(v) || !s.add(v))(new Set));
console.log(seen);
Using some function on arrays:
If any item in the array has an index number from the beginning is not equals to index number from the end, then this item exists in the array more than once.
// vanilla js
function hasDuplicates(arr) {
return arr.some( function(item) {
return arr.indexOf(item) !== arr.lastIndexOf(item);
});
}
function hasDuplicates(arr) {
var counts = [];
for (var i = 0; i <= arr.length; i++) {
if (counts[arr[i]] === undefined) {
counts[arr[i]] = 1;
} else {
return true;
}
}
return false;
}
// [...]
var arr = [1, 1, 2, 3, 4];
if (hasDuplicates(arr)) {
alert('Error: you have duplicates values !')
}
Simple Javascript (if you don't know ES6)
function hasDuplicates(arr) {
var counts = [];
for (var i = 0; i <= arr.length; i++) {
if (counts[arr[i]] === undefined) {
counts[arr[i]] = 1;
} else {
return true;
}
}
return false;
}
// [...]
var arr = [1, 1, 2, 3, 4];
if (hasDuplicates(arr)) {
alert('Error: you have duplicates values !')
}
function hasDuplicateString(strings: string[]): boolean {
const table: { [key: string]: boolean} = {}
for (let string of strings) {
if (string in table) return true;
table[string] = true;
}
return false
}
Here the in operator is generally considered to be an 0(1) time lookup, since it's a hash table lookup.
var elems = ['f', 'a','b','f', 'c','d','e','f','c'];
elems.sort();
elems.forEach(function (value, index, arr){
let first_index = arr.indexOf(value);
let last_index = arr.lastIndexOf(value);
if(first_index !== last_index){
console.log('Duplicate item in array ' + value);
}else{
console.log('unique items in array ' + value);
}
});
You have to create an empty array then check each element of the given array if the new array already has the element it will alert you.
Something like this.
var strArray = [ "q", "w", "w", "e", "i", "u", "r"];
let newArray =[];
function check(arr){
for(let elements of arr){
if(newArray.includes(elements)){
alert(elements)
}
else{
newArray.push(elements);
}
}
return newArray.sort();
}
check(strArray);
Use object keys for good performance when you work with a big array (in that case, loop for each element and loop again to check duplicate will be very slowly).
var strArray = ["q", "w", "w", "e", "i", "u", "r"];
var counting = {};
strArray.forEach(function (str) {
counting[str] = (counting[str] || 0) + 1;
});
if (Object.keys(counting).length !== strArray.length) {
console.log("Has duplicates");
var str;
for (str in counting) {
if (counting.hasOwnProperty(str)) {
if (counting[str] > 1) {
console.log(str + " appears " + counting[str] + " times");
}
}
}
}
This is the simplest solution I guess :
function diffArray(arr1, arr2) {
return arr1
.concat(arr2)
.filter(item => !arr1.includes(item) || !arr2.includes(item));
}
const isDuplicate = (str) =>{
return new Set(str.split("")).size === str.length;
}
You could use reduce:
const arr = ["q", "w", "w", "e", "i", "u", "r"]
arr.reduce((acc, cur) => {
if(acc[cur]) {
acc.duplicates.push(cur)
} else {
acc[cur] = true //anything could go here
}
}, { duplicates: [] })
Result would look like this:
{ ...Non Duplicate Values, duplicates: ["w"] }
That way you can do whatever you want with the duplicate values!
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/
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.