Add strings in an array - Javascript - javascript

I have an array of text:
var text = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");
I would like to add the elements in the array according to a set number and then store these in a new array. For example, if I pick 3, then the resulting strings in the new array (terms) would be: ["a b c", "d e f", "g h i", ...] etc
I looked at Join and I can't get this to work - it seems to only be able to add the entire array together. I'm guessing I need to use a nested loop, but I can't seem to get this to work. Here's my attempt:
//Outer loop
for (i = 0; i < text.length; i++) {
//Inner loop
for (j = i; j < i + $numberWords; j++) {
newWord = text[j];
newPhrase = newPhrase + " " + newWord;
}
terms.push(newPhrase);
i = i + $numberWords;
}

You can use various array functions like so:
var input = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");
var output = new Array();
var length = 3;
for (var i = 0; i < input.length; i += length) {
output.push(input.slice(i, i + length).join(" "));
}
alert(output);
Variant of the above example:
var input = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");
var output = new Array();
var length = 2;
while (input.length) {
output.push(input.splice(0, length).join(" "))
}
alert(output);

Here you go:
var text=new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s");
var n = 3;
var a = new Array();
for (var i = 0; i < Math.ceil(text.length / 3); i++)
{
var s = '';
for (var j = 0; (j < n) && ((i*n)+j < text.length) ; j++)
{
s += text[n*i+j] + ' ';
}
a.push(s.trim());
}

Related

How to push to an array given that the character is not already present in the array in javascript

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);

Get the point where the replace occurred in a replace

I'm trying to create a string increaser function that will take one string and raise it up one, for example:
000000 is the first string, then comes 000001, up to 000009 where it then goes onto 00000a up to 00000z.
My idea was that I will replace the last pattern (z) with the first (0), then, get the point where it was replaced and increase that by one in the pattern.
The code I tried to use:
cycler(string) {
//string="00000z"
var pos = string.replace('z', '0');
console.log(pos);
}
I sadly realized that the return of this function was the replaced version, not what I was after. Which makes total logical sense.
I'm wondering if there is a function in JavaScript for this functionality of finding where the all the replaces were made?
this way you can increase the string.
first you find the place you want to change. and then you change it
const range = ["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"];
cycler = function(string) {
const pos = string.match(/[0-9a-z]z/ )
return pos === null ? string.length - 1 : pos.index
}
inc = function(string,pos) {
let rangeIndex = range.indexOf(string[pos]);
rangeIndex++;
let arr = string.split("");
arr[pos] = range[rangeIndex];
return arr.join("");
}
var string = '00002z';
const pos = cycler(string);
alert(inc(string,pos))
If I understand correctly, you want to replace all occurrences.
cycler(string) {
//string="00000z"
var pos = string.replace(/z/g, '0');
console.log(pos);
}
Ignore if misunderstood. Thanks.
I don't think there is any inbuilt method for this but you can create your customized logic as follows:
var orgstr = '000000';
var arr = ["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"];
function getNextStr(str) {
var count = (str.match(/0/g) || []).length;
var rStr = ""
var found = str.replace(/0/g, '');
var next = getNext(found);
var nexIn = arr.indexOf(found) + 1;
if (next.length != found.length) {
rStr = str.slice(0, count - 1) + next;
} else {
rStr = str.slice(0, count) + next;
}
return rStr;
}
function getNext(fou) {
var str = '';
var nextTobeGrown = true;
for (var i = fou.length - 1; i >= 0; i--) {
var x = fou.substring(i + 1, i);
var ind = arr.indexOf(x);
if (nextTobeGrown) {
if (ind + 1 < arr.length) {
str += arr[ind + 1];
nextTobeGrown = false;
} else {
str += arr[0]
}
} else {
str += x;
}
}
//console.log(str)
if (nextTobeGrown) {
str += arr[0];
}
return str.split("").reverse().join("");;
}
var rst;
for (var i = 0; i < 160; i++) {
var org = i == 0 ? orgstr : rst;
rst = getNextStr(org);
console.log(rst)
}

Simple Password Encryption with Javascript

This is what I currently have but it is only printing the first Letter in the encryption. Where am I going wrong?
function crypto(){
var password = "Pizza2Day";
var flag = 0;
var encryptedPassword= "";
var originalValues = ["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 encryptedValues = ["m", "h","t","f","g","k","b","p","j","w","e","r","q","s","l","n","i","u","o","x","z","y","v","d","c","a"];
for (var i=0; i < password.length; i++){
flag=0;
for (var r = 0; r < originalValues.length; r++){
if (originalValues[r] == password.charAt(i)){
encryptedPassword = encryptedPassword + encryptedValues[r];
flag = 1;
break;
} else if (originalValues[r].toUpperCase() == password.charAt(i)) {
encryptedPassword = encryptedPassword +
encryptedValues[r].toUpperCase();
flag = 1;
break;
}
}
if (flag == 0) {
encryptedPassword = encryptedPassword + password.charAt(i);
}
return encryptedPassword;
}
}
console.log("New Password: " + crypto());
You need to put the return statement outside the for loop:
function crypto() {
var password = "Pizza2Day";
var flag = 0;
var encryptedPassword = "";
var originalValues = ["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 encryptedValues = ["m", "h", "t", "f", "g", "k", "b", "p", "j", "w", "e", "r", "q", "s", "l", "n", "i", "u", "o", "x", "z", "y", "v", "d", "c", "a"];
for (var i = 0; i < password.length; i++) {
flag = 0;
for (var r = 0; r < originalValues.length; r++) {
if (originalValues[r] == password.charAt(i)) {
encryptedPassword = encryptedPassword + encryptedValues[r];
flag = 1;
break;
} else if (originalValues[r].toUpperCase() == password.charAt(i)) {
encryptedPassword = encryptedPassword +
encryptedValues[r].toUpperCase();
flag = 1;
break;
}
}
if (flag == 0) {
encryptedPassword = encryptedPassword + password.charAt(i);
}
}
return encryptedPassword;
}
console.log("New Password: " + crypto());
You could take another aproach by using strings instead of arrays for the characters and take String#indexOf for getting the index of the given string.
A check if the index is -1, the value for a missing character in the string ins not necessary, because this value is taken as index for the the encrypted string. This returns either a character or undefined, which is a falsy. In combination with a following logical OR ||, the next value is taken, in this case the original character of the string to encode.
After a check if the original character is an upper case character, the character is converted to uppercase and then added to the result string.
function crypto() {
var password = "Pizza2Day",
encryptedPassword = "",
original = "abcdefghijklmnopqrstuvwxyz",
encrypted = "mhtfgkbpjwerqslniuoxzyvdca",
i, character;
for (i = 0; i < password.length; i++) {
character = encrypted[original.indexOf(password[i].toLowerCase())] || password[i];
if (password[i] === password[i].toUpperCase()) {
character = character.toUpperCase();
}
encryptedPassword += character;
}
return encryptedPassword;
}
console.log("New Password: " + crypto());

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/

Append Div with Multiple Child Divs Using For Loop

I realize that this has been asked a million times... but sorting through all the ones I've found, I haven't found one that really explains it well.
HTML:
<div id="alphabet"></div>
JS:
var 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"];
var target = document.getElementById('alphabet');
for (i = 0; i < 26; i++) {
var newLink = document.createElement('div');
target.appendChild = newLink;
newLink.innerHTML = alphabet[i];
}
alert(alphabet);
alert(newLink);
alert(target);
Obviously there is something I'm missing... With such a simple example I can't believe I'm having this much trouble. Any help is much appreciated, thanks in advance!
Basically node.appendChild(node) is a function.
target.appendChild(newLink);
And your full code would be,
for (i = 0; i < 26; i++) {
var newLink = document.createElement('div');
newLink.innerHTML = alphabet[i];
target.appendChild(newLink);
}

Categories

Resources