Reverse whole string while keeping the spaces at the same position - javascript

This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
for (var i = spaces.length - 1; i >=0; i = i - 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."
Then "array2" is an array of "array1" reversed.
Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.
Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".
I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.

You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);

Here is my best crack at it.
const reverseStr = (input) => {
const revArr = input.replaceAll(' ', '').split('').reverse();
for (let i = 0; i < revArr.length; i++) {
if (input[i] === ' ') revArr.splice(i, 0, ' ');
}
return revArr.join('');
}

let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
// console.log(val.split('').reverse().join(''))
return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))

Related

how to get distinct value from an array javascript

how can i get elements uniquely from an array if aa is twice time it should not count in a result if it is if a is three times it should count 1
var string = "aaabbccddde" // Expected result ade
var toArray = string.split("")
console.log(toArray)
var newArr = []
for(let i =0; i<toArray.length; i++) {
if(newArr.indexOf(toArray[i]) === -1) {
newArr.push(toArray[i])
}
}
console.log(newArr)
can't find the solution yet please guide thank
Maybe this function can help you:
function getUniques(str) {
const uniques = [];
const strs = str.split("");
for (let i = 0; i < strs.length; i++) {
const elm = strs[i];
for (let j = i; j < strs.length; j++) {
if(elm === uniques[uniques.length - 1]) break;
if (elm !== strs[j + 1]) {
uniques.push(elm);
break;
}
}
}
return uniques.join("");
}
Sample:
getUniques("aaaadaaabbbcccdeeeee22222222222232") // adabcde232

JavaScript - find the same first element using for loop

I've got to create var with few elements:
var arrNum = [4,7,5,3,4,5,6,7,8,10]
I need to find first number that is the same in array using for loop. So it will be "4" and "4"
I need to create var sameIndex and adjust the same number to sameIndex and print after for loop
So I did loop
for(var i = 0; i < arrNum.length; i++){
console.log("")
console.log("Loop number is " + i)
if(arrNum[i] === arrNum[i]{
break
sameIndex = going[i]
}
}
console.log(sameIndex)
It's not working.
One way would be to use Array#indexOf. It returns the first index of the given element in the array:
var arrNum = [4, 7, 5, 3, 4, 5, 6, 7, 8, 10];
var i;
var sameIndex = -1;
for (i = 0; i < arrNum.length; i++) {
if (arrNum.indexOf(arrNum[i]) !== i) {
console.log('This is the second occurrence of', arrNum[i]);
sameIndex = arrNum.indexOf(arrNum[i]);
break;
}
}
console.log('The indices are', sameIndex, 'and', i);
If you're looking to get the first duplicate, then use :
var arrNum = [4,7,5,3,4,5,6,7,8,10];
function firstDuplicate(array){
var history = [];
for(var element of array){
if(history.indexOf(element)<0)
//not in the history yet
history.push(element);
else
return element;
}
return null; //or any distinctive value
}
var fDup = firstDuplicate(arrNum);
You could take a hash table and display the value.
var array = [4, 7, 5, 3, 4, 5, 6, 7, 8, 10],
hash = Object.create(null),
i;
for (i = 0; i < array.length; i++) {
if (hash[array[i]]) {
console.log('first dupe: ' + array[i]);
break;
}
hash[array[i]] = true;
}
A working script:
var arrNum = [4,7,5,3,4,5,6,7,8,10];
var sameIndex = -1, going = new Array();
for(var j = 0; j < arrNum.length; j++) {
for(var i = 1; i < arrNum.length; i++){
console.log("Loop number is " + j + ", " + i)
if(arrNum[i] === arrNum[j]){
sameIndex = i;
break;
}
}
if(sameIndex > 0) {
console.log(j, sameIndex)
break;
}
}
var arrNum = [4,7,5,3,4,5,6,7,8,10];
for(var i = 0; i < arrNum.length; i++){
for(var j = i+1; j < arrNum.length; j++) {
if(arrNum[i] === arrNum[j]) {
console.log('value: '+arrNum[i]+' index1: '+i+' index2: '+j);
}
}
}
Iterate over the original array and if the value is not in a comparison array - push it into a common numbers array. The first item in that common numbers array is the target.
var origArray = [4,7,5,3,4,5,6,7,8,10];
var newArray = [];
var commonNums = [];
origArray.forEach(function(item,i) {
newArray.indexOf(item) == -1
? newArray.push(item)
: commonNums.push({item: item, index:i});
})
if(commonNums.length > 0) {
var firstCommonNum = commonNums[0].item;
var firstCommonNumIndex = commonNums[0].index;
console.log("common number " + firstCommonNum);
console.log("Loop number is " + firstCommonNumIndex);
}

Generate chunks from string

before going to problem, i want to generate dynamically like
temp = word[i] for 2,
temp = word[i-1] + word [i] for 3,
temp = word[i-2] + word[i-1] + word [i] for 4
I explained with code and what i have tried
function produceTwoChArray(word) {
var temp = "";
var tempArr = [];
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === 2) {
tempArr.push(temp);
}
temp = word[i];
}
return tempArr;
}
produceTwoChArray("breaking")
above code will produce result as :
["br", "re", "ea", "ak", "ki", "in", "ng"]
So inside the for loop if i change to below codes to produce three letters then
if (temp.length === 3) {
tempArr.push(temp);
}
temp = word[i-1] + word[i];
Result:
["bre", "rea", "eak", "aki", "kin", "ing"]
so adding word[i-1], word[i-2] with temp length 3, 4 and so on..
For dynamically creating the temp statement, i created these Function
1)
function generateWordSequence(n) {
var n = n - 2;
var temp1 = [];
for (var j = n; j >= 0; j--) {
temp1.push("word[i - " + j + "]");
}
temp1 = temp1.join('+').toString();
return temp1;
}
2)
function generateWordSequence(n, word) {
var n = n - 2;
var temp1 = "";
for (var j = n; j >= 0; j--) {
temp1 = temp1 + word[i - j];
}
return temp1;
}
But both above try's are returning as string so it didnt work. When i invoke above fn in produceTwoChArray fn like this
function produceTwoChArray(word, n) {
var temp = "";
var tempArr = [];
var retVar = generateWordSequence(n, word);
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === n) {
tempArr.push(temp);
}
temp = retVar;
}
return tempArr;
}
When i tried those all logic inside produceTwochArray itself , i also didnt work.
Please help me out here.
You could take a double slice with mapping part strings.
function part(string, count) {
return [...string.slice(count - 1)].map((_, i) => string.slice(i, i + count));
}
console.log(part("breaking", 2));
console.log(part("breaking", 3));
console.log(part("breaking", 4));
You can use slice method in order to obtain a more easy solution.
function produceArray(str,n){
return str=str.split('').map(function(item,i,str){
return str.slice(i,i+n).join('');
}).filter(a => a.length == n);
}
console.log(produceArray("breaking",2));
console.log(produceArray("breaking",3));
console.log(produceArray("breaking",4));
console.log(produceArray("breaking",5));
console.log(produceArray("breaking",6));

Two chunks of code work separately but not together, where do i err?

Why is it that the following works fine:
var howMany = prompt("How many numbers?");
var myArray = [];
for(var i = 0; i < howMany; i++){
myArray.push(prompt("Enter a number"));
}
alert(myArray);
The code above is intended to ask user how many numbers are they going to put into an array, and it displays the array.
This chunks of code below seems to be fine too.
There is a provided array.
Then the code checks whether the numbers are actually numbers.
After that it adds all the numbers together.
var myArray = [1,2,3,4,5];
isDataUniform(myArray);
function isDataUniform(array) {
var first = array[0];
var length = array.length;
for (i=0; i<length; i++){
if(typeof array[i]!== typeof first){
return false;
}
}
return true;
}
if (isDataUniform(myArray) === true){
add(myArray);
} else {
console.log("cant do adding");
}
function add(array) {
var f = 0;
var length = array.length;
for (i=0; i<length; i++){
f+= array[i];
}
alert("The result of addition of this set: " + myArray + " is: " + f);
}
but when i combine the two it does not work. It does not add the numbers.
var howMany = prompt("How many numbers?");
var myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(prompt("Enter a number"));
}
isDataUniform(myArray);
function isDataUniform(array) {
var first = array[0];
var length = array.length;
for (i = 0; i < length; i++) {
if (typeof array[i] !== typeof first) {
return false;
}
}
return true;
}
if (isDataUniform(myArray) === true) {
add(myArray);
} else {
console.log("can't do adding");
}
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += array[i];
}
alert("Result of addition of this set: " + myArray + " is: " + f);
}
Can you be so kind to correct me?
The return value from prompt is a string, not a number.
var n = prompt("Enter a number");
alert("typeof(n) = " + typeof(n));
Even if you enter a numeric value, the code above will display "typeof(n) = string".
You must convert the string into a number.
var howMany = prompt("How many numbers?");
var myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(parseInt(prompt("Enter a number"), 10));
}
The prompt function saves strings, so the problem here is that you are trying to make a sum of strings. Just add a typecast in the add function and the script will work correctly:
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += parseInt(array[i]);
}
}
var howMany = prompt("How many numbers?"),
myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(parseInt(prompt("Enter a number"),10));
}
function isDataUniform(array) {
for (i = 0; i < array.length; i++) {
if (typeof array[i] !== "number") {
return false;
}
}
return true;
}
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += array[i];
}
alert("Result of addition of this set: " + myArray + " is: " + f);
}
if (isDataUniform(myArray) === true) {
add(myArray);
} else {
console.log("can't do adding");
}

Why does this code work with my array, but not when I typed in an array of strings? JavaScript

This code works when I have my array of arrays of numbers, but not when I typed in an array of arrays of strings; I did change the code to use .length afterward for the strings, but that helps. The error is with the line of "arr[i].reduce(function (onea, twoa) {" being an undefined function in the second version.
Oh, #user1600124, that prompt might be the error, even though I did still type in "[ ["one", "two", "three"], ["one1", "two2", "three3"] ]", it changed that all into a string. You have solved it, I think, but is there a way for user input without prompt. Thanks, #user1600124 for your solution!
var ArrayWidth = function(arr){
var ret = [], i;
for (i = 0; i < arr.length; i++) {
arr[i].reduce(function (onea, twoa) {
return ret[i] = Math.max(onea.length, twoa.length); //added ".length" to stings version
}, 0); //added ",0" to strings version
ret[i] = ret[i].toString().length;
}
return ret;
}
Working full code of array of arrays of numbers:
//Draws Non=Jagged Table with columns be the arrays in the array of arrays and the first being the heading.
var arrays = [
[111111, 22222, 333],
[444444444, 534334, 63],
[73, 83748395, 9343],
[279571, 327894598571490581, 34815, 2]
];
function ArrayHeight (arr) {
var ret = [], i, j;
for(i = 0; i < arr.length; i++){
window["a"+i] = arr[i];
ret[i] = window["a"+i];
for(j = 0; j < ret[i].length; j++)
ret[i][j] = ret[i][j].toString();
}
return ret;
}
var ArrayWidth = function(arr){
var ret = [], i;
for (i = 0; i < arr.length; i++) {
arr[i].reduce(function (onea, twoa) {
return ret[i] = Math.max(onea, twoa);
});
ret[i] = ret[i].toString().length;
}
return ret;
}
function addSpace (){
var ret = ArrayHeight(arrays);
console.log(ret);
var widthOfRet = ArrayWidth(arrays);
console.log(widthOfRet);
var i, j, k;
for(j = 0; j < ret.length; j++){
for(k = 0; k < (ret[j].length); k++){
for(i = ret[j][k].length; i < (widthOfRet[j] + 1); i++){
ret[j][k] = ret[j][k] + " ";
}
}
}
return ret;
}
var drawTable = function(){
var ret = addSpace();
var ArrayWid = ArrayWidth(arrays);
var table = "", retFirst = "", retSecond = "", totaled = 0, i, j;
for (i = 0; i < ArrayWid.length; i++)
totaled = totaled + ArrayWid[i];
for(i = 0; i < ret.length; i++)
retFirst = retFirst + ret[i][0];
for(i = 0; i < (totaled + ret.length); i++)
retSecond = retSecond + "-";
for(j = 0; j < ret.length; j++)
for(i = 0; i < ret[j].length; i++)
window["reti"+i] = "";
for(j = 0; j < ret.length; j++)
for(i = 0; i < ret[j].length; i++)
window["reti"+i] = window["reti"+i] + ret[j][i];
table = retFirst + "\n" + retSecond;
for(i = 1; window["reti"+i] != undefined; i++)
table = table + "\n" + window["reti"+i];
return table;
}
console.log(drawTable());
nonworking with array of arrays of strings:
//Draws Non-Jagged Table with columns be the arrays in the array of arrays and the first being the heading.
var arrays = prompt("To draw a table, type in an array of arrays. Each array is a column and the first is the heading. Cannot be jagged.", "[ [ , ... ], [, ... ], ... ]");
function ArrayHeight (arr) {
var ret = [], i, j;
for(i = 0; i < arr.length; i++){
window["a"+i] = arr[i];
ret[i] = window["a"+i];
for(j = 0; j < ret[i].length; j++)
ret[i][j] = ret[i][j].toString();
}
return ret;
}
var ArrayWidth = function(arr){
var ret = [], i;
for (i = 0; i < arr.length; i++) {
arr[i].reduce(function (onea, twoa) {
return ret[i] = Math.max(onea.length, twoa.length);
}, 0);
ret[i] = ret[i].toString().length;
}
return ret;
}
function addSpace (){
var ret = ArrayHeight(arrays);
console.log(ret);
var widthOfRet = ArrayWidth(arrays);
console.log(widthOfRet);
var i, j, k;
for(j = 0; j < ret.length; j++){
for(k = 0; k < (ret[j].length); k++){
for(i = ret[j][k].length; i < (widthOfRet[j] + 1); i++){
ret[j][k] = ret[j][k] + " ";
}
}
}
return ret;
}
var drawTable = function(){
var ret = addSpace();
var ArrayWid = ArrayWidth(arrays);
var table = "", retFirst = "", retSecond = "", totaled = 0, i, j;
for (i = 0; i < ArrayWid.length; i++)
totaled = totaled + ArrayWid[i];
for(i = 0; i < ret.length; i++)
retFirst = retFirst + ret[i][0];
for(i = 0; i < (totaled + ret.length); i++)
retSecond = retSecond + "-";
for(j = 0; j < ret.length; j++)
for(i = 0; i < ret[j].length; i++)
window["reti"+i] = "";
for(j = 0; j < ret.length; j++)
for(i = 0; i < ret[j].length; i++)
window["reti"+i] = window["reti"+i] + ret[j][i];
table = retFirst + "\n" + retSecond;
for(i = 1; window["reti"+i] != undefined; i++)
table = table + "\n" + window["reti"+i];
return table;
}
console.log(drawTable());
alert("Your table is in the console.log");
my html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script language="javascript">
//script was here
</script>
</body>
</html>
Thanks! :)
You are calling the reduce function on the content of the input array.
When you have array of arrays of numbers, arr[i] is an array, and hence has the reduce method
When you have array of strings, arr[i] is a string, and do not have the reduce method you tried to use. So you end up with errors
Try this:
function ArrayWidth(ary){
var r = [];
for(var i=0,l=ary.length; i<l; i++) {
r[i] = ary[i].reduce(function(a, b){
return Math.max(a, b);
}, 0);
}
return r;
}

Categories