This question already has answers here:
To find Index of Multidimensional Array in Javascript
(7 answers)
Closed 3 years ago.
I want to where is placed an element in an multidimentional array like that :
var letterVariations = [
[' ','0','1','2','3','4','5','6','7','8','9'],
['A','a','B','b','C','c','D','d','E','e',';'],
['Â','â','F','f','G','g','H','h','Ê','ê',':'],
['À','à','I','i','J','j','K','k','È','è','.'],
['L','l','Î','î','M','m','N','n','É','é','?'],
['O','o','Ï','ï','P','p','Q','q','R','r','!'],
['Ô','ô','S','s','T','t','U','u','V','v','“'],
['W','w','X','x','Y','y','Ù','ù','Z','z','”'],
['#','&','#','[','(','/',')',']','+','=','-'],
];
var coordinates = letterVariations.indexOf('u');
console.log(coordinates);
// Want to know that 'u' is 7 in the 7th array
Is it possible ?
Run a simple for loop and check if the character exists in the inner array using indexOf. return immediately once a match is found
var letterVariations = [
[' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', ';'],
['Â', 'â', 'F', 'f', 'G', 'g', 'H', 'h', 'Ê', 'ê', ':'],
['À', 'à', 'I', 'i', 'J', 'j', 'K', 'k', 'È', 'è', '.'],
['L', 'l', 'Î', 'î', 'M', 'm', 'N', 'n', 'É', 'é', '?'],
['O', 'o', 'Ï', 'ï', 'P', 'p', 'Q', 'q', 'R', 'r', '!'],
['Ô', 'ô', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', '“'],
['W', 'w', 'X', 'x', 'Y', 'y', 'Ù', 'ù', 'Z', 'z', '”'],
['#', '&', '#', '[', '(', '/', ')', ']', '+', '=', '-'],
];
function getCoordinates(array, char) {
for (let i = 0; i < array.length; i++) {
const i2 = array[i].indexOf(char);
if (i2 !== -1)
return [i, i2]
}
return undefined
}
console.log(getCoordinates(letterVariations, 'u'))
console.log(getCoordinates(letterVariations, '#'))
Note: This returns the indexes and it is zero-based. If you want [7, 7], you need to return [i+1, i2]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
const letterVariations = [
[' ','0','1','2','3','4','5','6','7','8','9'],
['A','a','B','b','C','c','D','d','E','e',';'],
['Â','â','F','f','G','g','H','h','Ê','ê',':'],
['À','à','I','i','J','j','K','k','È','è','.'],
['L','l','Î','î','M','m','N','n','É','é','?'],
['O','o','Ï','ï','P','p','Q','q','R','r','!'],
['Ô','ô','S','s','T','t','U','u','V','v','“'],
['W','w','X','x','Y','y','Ù','ù','Z','z','”'],
['#','&','#','[','(','/',')',']','+','=','-'],
];
function getIndexOfLetter(letter) {
return letterVariations.reduce((result, values, index) => {
if (result[0] > -1) return result;
const found = values.indexOf(letter);
return found > -1 ? [Number(index), found] : result;
}, [-1, -1])
}
console.log(getIndexOfLetter('k'))
Related
hey i want to ask a question, how i can save my data in a json file, i want to see a passwords & usernames my users, i try added but my json file save for a 1 user data only, i want to add a all users.
js
var newusername = req.body.newusername;
newpassword = req.body.newpassword;
letters = ['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'];
cap_letters = ['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'];
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
allchars = letters + cap_letters + numbers + ['_'];
goodusername = true;
for(let i of newusername){
if(!allchars.includes(i)){
goodusername = false;
}
}
if(goodusername){
db.list().then(keys => {
if(keys.includes(newusername)){
res.send("Username taken. ");
} else if(newusername == ""){
res.send("Please enter a username.");
} else if(newpassword == ""){
res.send("Please enter a password.")
} else{
db.set(newusername, newpassword).then(() => console.log(`New Account Created Username : ${newusername} || Pass : ${newpassword}`));
//////////////////////////////////// json code ///////////////////////////////////////
fs.writeFile('account.json', newusername, finished);
function finished(err){
console.log('all set.')
}
/////////////////////////////////////////////////////////////////////////////////////
res.cookie("loggedIn", "true")
res.cookie("username", newusername);
res.redirect("/");
}
});
} else{
res.send("Username can only contain alphanumeric characters and underscores.")
}
});```
The issue is that every time you call writeFile, the previous content of the file is obliterated.
The function you’re looking for is fs.appendFile
// Overwrite file contents
fs.writeFile('account.json', newusername, finished);
// Add to file contents
fs.appendFile('account.json', newusername, finished);
Edit: Bonus tip
Here’s a nice way to setup the arrays of characters and numbers. Lowercase in this example:
const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
/*
pattern:
e,b,c,d,i,f,g,h,o,j,k,l,m,n,u,p,q,r,s,t,a,v,w,x,y,z
I want to sort my words from arr by 2nd letter of each word according to my given pattern.
['aobcdh','aiabch','obijkl']
#output should be:
obijkl
aiabch
aobcdh
*/
// I tried this way:
let pattern = ['e', 'b', 'c', 'd', 'i', 'f', 'g', 'h', 'o', 'j', 'k', 'l', 'm', 'n', 'u', 'p', 'q', 'r', 's', 't', 'a', 'v', 'w', 'x', 'y', 'z']
let arr = ['aiabch', 'aobcdh', 'obijkl', 'apcsdef', 'leeeeeeeeeeeeeeee']
let refArr = []
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < pattern.length; j++) {
if (pattern[j] === arr[i][1]) {
refArr.push(j)
}
}
}
console.log(refArr)
// now what next?
You can use the sort method and the indexOf function
let pattern = ['e', 'b', 'c', 'd', 'i', 'f', 'g', 'h', 'o', 'j', 'k', 'l', 'm', 'n', 'u', 'p', 'q', 'r', 's', 't', 'a', 'v', 'w', 'x', 'y', 'z']
let arr = ['aiabch', 'aobcdh', 'obijkl', 'apcsdef', 'leeeeeeeeeeeeeeee']
const newArr = arr.sort((a, b) => pattern.indexOf(a[1]) - pattern.indexOf(b[1]))
console.log(newArr)
You could generate an object with the order values and sort by this values.
If necessary convert the key to lower case and/or take a default value for sorting unknown letters to front or end.
const
pattern = 'ebcdifghojklmnupqrstavwxyz',
array = ['aobcdh', 'aiabch', 'obijkl'],
order = Object.fromEntries(Array.from(pattern, (l, i) => [l, i + 1]));
array.sort((a, b) => order[a[1]] - order[b[1]]);
console.log(array);
Also, you can try this if you does not know Array methods.
let pattern = ['e', 'b', 'c', 'd', 'i', 'f', 'g', 'h', 'o', 'j', 'k', 'l', 'm', 'n', 'u', 'p', 'q', 'r', 's', 't', 'a', 'v', 'w', 'x', 'y', 'z'], arr = ['aiabch', 'aobcdh', 'obijkl', 'apcsdef', 'leeeeeeeeeeeeeeee'], refArr = []
arr.forEach(a => pattern.includes(a[2]) ? refArr.push(a) : null)
console.log(refArr)
You must reverse your cross loops:
for(let i = 0; i < pattern.length; ++i) {
for(let j = 0; j < arr.length; ++j) {
if(pattern[i] === arr[j][1]) refArr.push(arr[j]);
}
}
I want to generate a random password of length of 16 characters containing numbers, alphabets and special characters, but no two special characters should be adjacent
the special characters i am using are ~!##$%^&*()_+-={}[]:;\?,.|\\
generateRandomPasswordSelection = function (length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~!##$%^&*()_+-={}[]:;\?,.|\\';
var result ='';
for(var i=1; i>=1;i++){
result = '';
for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
if(result.match(new RegExp(/(?!.*[~!##$%^&*()_+={}[\]:;\?,.|\\-]{2})[A-Za-z0-9]{1,16}$/))){
console.log(result,'---------------->', 'BREAk')
break;
}
}
}
generateRandomPasswordSelection(16,'aA#!');
Above one is the code i have tried, but didn't work.How to achieve this?
Uses ES6 syntax, hopefully more readable.
const getRandomElement = arr => {
const rand = Math.floor(Math.random() * arr.length);
return arr[rand];
}
const generateRandomPasswordSelection = (length) => {
const uppercase = ['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'];
const lowercase = ['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'];
const special = ['~', '!', '#', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '{', '}', '[', ']', ':', ';', '?', ', ', '.', '|', '\\'];
const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const nonSpecial = [...uppercase, ...lowercase, ...numbers];
let password = '';
for (let i = 0; i < length; i++) {
// Previous character is a special character
if (i !== 0 && special.includes(password[i - 1])) {
password += getRandomElement(nonSpecial);
} else password += getRandomElement([...nonSpecial, ...special]);
}
return password;
}
const password = generateRandomPasswordSelection(16);
console.log(password);
If I have the code below to generate random characters, how can I code it to generate those same characters excluding some values? I.e. corresponding to var charactExclude.
Ex:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
var charactExclude = document.getelementbyID(character).content.text
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result
}
console.log(makeid(10))
Here's how I would go about this:
First select your element containing the excluded characters (You have some errors in your JS) You can split this into an array using .split('') and use the [...new Set(Your array here)] pattern to remove duplicates at this point.
Then create a new variable for the filtered string, and loop through replacing the characters you do not want to include.
Finally, use this new variable in the creation of your string.
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactExclude = [
// Using a Set efficiently removes duplicates, and will speed up the loop below, and the ... expands them back into an array
...new Set(
// Using split('') will turn the string into an array of characters
document.getElementById("character").innerText.split('')
)
];
// Create a new variable, and then loop through the charactExclude array, removing undesired chars
var charactersFiltered = characters
for (var i = 0; i < charactExclude.length; i++) {
charactersFiltered = charactersFiltered.replace(charactExclude[i], '')
}
for (var i = 0; i < length; i++) {
result += charactersFiltered.charAt(Math.floor(Math.random() * charactersFiltered.length));
}
return result
}
console.log(makeid(100))
<div id="character">ABCDEFG</div>
I admit this might be a little tortuous as solution...
/*
* Char codes ranges:
* 0-9 -> 48-57
* A-Z -> 65-90
* a-z -> 97-122
*/
function makeId(idLength, charsToExclude = []) {
// list of all invalid char codes between '0' (char code 48) and 'z' (char code 122)
const invalidCharCodes = [58, 59, 60, 61, 62, 63, 64, 91, 92, 93, 94, 95, 96];
// add to the invalid char list any char passed as parameter
if (charsToExclude.length > 0) {
charsToExclude.forEach(char => invalidCharCodes.push(char.charCodeAt(0)))
}
let id = '';
while (id.length < idLength) {
let charCode;
do {
charCode = Math.floor(Math.random() * (122 - 48 + 1)) + 48;
} while (invalidCharCodes.indexOf(charCode) >= 0)
id += String.fromCharCode(charCode);
}
return id;
}
// test
console.log('should return an ID containing digits and letters (either lower or upper case):', makeId(10));
console.log('should return an ID containing only digits:', makeId(10, ['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']));
console.log('should return an ID containing only letters (either lower or upper case):', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']));
console.log('should return an ID containing only lower case letters:', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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']));
console.log('should return an ID containing only upper case letters:', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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']));
console.log('should return an ID containing only 0s:', makeId(10, ['1', '2', '3', '4', '5', '6', '7', '8', '9', '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']));
You could use Array.filter for that
const alphabetAndNumbers = () => [...Array(26)]
.map((x, i) => String.fromCharCode(i + 65))
.concat([...Array(26)].map((x, i) => String.fromCharCode(i + 97)))
.concat([...Array(10)].map((x, i) => `${i}`));
console.log(`Your id: ${createRandomId(10)}`);
function createRandomId(len) {
let characters = alphabetAndNumbers();
console.log(`[characters] initial ${characters.join("")}`);
//retrieve characters to exclude from the template element and split it to an array
const excludes = document.querySelector("#excludes").content.textContent.split("");
// filter initial characters array to exclude the characters in [excludes]
// now [characters] is an array too
characters = characters.filter(c => !~excludes.indexOf(c));
console.log(`excluded ${excludes.join("")}`)
console.log(`[characters] now ${characters.join("")}`);
// create an array with length [len], map characters (pseudo random) into it
// and return the joined array
return [...Array(len)]
.map(v => characters[Math.floor(Math.random() * characters.length)])
// ^ characters is array, so you can pick an element from it
.join("");
}
// easier may be to initially use a subset
const createRandomIdSimple = (len, chars) => [...Array(len)]
.map(v => chars[Math.floor(Math.random() * chars.length)])
.join("");
const chars4Id = document.querySelector("#chars4RandomId").content.textContent.split("");;
console.log(`Your id from createRandomSimple: ${createRandomIdSimple(10, chars4Id)}`);
<template id="excludes">DWX23Aal0gn</template>
<template id="chars4RandomId">BCEFGHIJKLMNOPQRSTUVYZbcdefhijkmopqrstuvwxyz1456789</template>
Bonus: rewritten to a factory function for creating random Id's
const randomId = RandomIdFactory();
const log = Logger();
log(`Lets create 25 pseudo random id's of length 32`,
`without "l" (lowercase L) and "0" (zero):\n`,
[...Array(25)].map(x => randomId(32, "l0")).join("\n"));
function RandomIdFactory() {
const characters = [...Array(26)]
.map((x, i) => String.fromCharCode(i + 65))
.concat([...Array(26)].map((x, i) => String.fromCharCode(i + 97)))
.concat([...Array(10)].map((x, i) => `${i}`));
return (len, excludes) => {
const chars = excludes &&
characters.filter(c => !~excludes.indexOf(c)) ||
characters;
return [...Array(len)]
.map(v => chars[Math.floor(Math.random() * chars.length)])
.join("");
};
}
function Logger() {
const logEl = document.querySelector("#log") || (() => {
document.body.append(Object.assign(document.createElement('pre'), {id:"log"}));
return document.querySelector("#log");
})();
return (...strs) => strs.forEach(s => logEl.textContent += `${s}\n`);
}
I am trying to create an text encrypter, but when i entered this code, nothing happens. What is wrong with my code?
function Encrypt(txt) {
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'}
for (i = 0; i < txt.length; i++) {
var chr = txt.charAt(i);
var pos = chars.indexOf(chr);
if (pos == chars.length) {
pos = 0;
}
else {
pos = pos++
}
txt.charAt(i) = chars[pos];
}
alert(txt);
}
You need
array [] instead of object {},
some declared variables
an empty result string newText, a string is read only with the character access
a valid check if the letter is not in the array
increment pos without assignment.
append the result string with the encoded character
function Encrypt(txt) {
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'],
i, newText = '', chr, pos;
for (i = 0; i < txt.length; i++) {
chr = txt[i];
pos = chars.indexOf(chr);
if (!~pos) {
pos = 0;
} else {
pos++;
}
newText += chars[pos];
}
document.write(newText);
}
Encrypt('test');
Because this is not an array, but object... and object has to have "index" : "value" structure.
Change this:
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'}
to this:
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']
Not considering the errors well described in the other answers, my proposal to encrypt a string is:
function Encrypt(txt) {
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'];
var txtResult = txt.split('').map(function(val) {
var pos = chars.indexOf(val);
return chars[(pos == chars.length) ? 0 : (pos + 1)];
}).join('');
document.write(txtResult);
}
Encrypt('gaemaf');