I am getting "undefined" while adding charcters in my array in javascript - javascript

Here is my code can someone just explain why I am getting undefined?? I have split the words and then reverse them and after reversing I tried to store them in a different array.
Thank you
const text = document.querySelector("#text");
const reverseText = document.querySelector("#reverseText");
let words = text.innerHTML.split("").reverse();
console.log(words);
let reversedWords = [];
let counter = 0;
for (var i = 0; i <= words.length - 1; i++) {
if (words[i] != " ") {
reversedWords[counter] += words[i];
} else {
counter++;
}
}
console.log(reversedWords);
<p id="text">hello nixit</p>
<p id="reverseText"></p>

Your issue is that the first time you try and access reversedWords[counter], it is undefined because you've initialised reversedWords to be an empty array.
Without changing much of your code (because you said you're doing it this way as a challenge), you could try initialising reversedWords to have the appropriate number of elements, initialised to empty strings
const content = text.textContent;
const words = content.split("").reverse();
const reversedWords = Array.from({ length: content.split(" ").length }, () => "");

You're using an array so you need to push things into it, and then join it up into a new string once the iteration is done.
const text = document.querySelector('#text');
const reverseText = document.querySelector('#reverseText');
function reverse(str) {
// `split` the string on the spaces
const words = str.split(' ');
const reversedWords = [];
for (let i = 0; i < words.length; i++) {
// For each word split, reverse, and then rejoin it
const word = words[i].split('').reverse().join('');
// And then add the word to the array
reversedWords.unshift(word);
}
// Return the completed array
return reversedWords;
}
const str = text.textContent;
reverseText.textContent = JSON.stringify(reverse(str));
<p id="text">hello nixit</p>
<p id="reverseText"></p>
Additional documentation
unshift

I suggest using a string instead of an array. Then you can split it to turn it into an array.
const reversedChars = 'hello nixit'.split("").reverse()
const reversedWords = ''
reversedChars.forEach(char => {
reversedWords += char
})
const reversedWordsArray = reversedWords.split(' ')
console.log(reversedWords)
// Output: tixin olleh
console.log(reversedWordsArray)
// Output: [ 'tixin', 'olleh' ]

Thanks to #phil and #Andy,
I am new learner who will learn and read all the use of Array.from() and than use it, but till than I have made something like this.
const text = document.querySelector("#text");
const reverseText = document.querySelector("#reverseText");
let words = text.innerHTML.split("").reverse();
let reversedWords = new Array();
let counter = 0;
let firstChar = 0;
for (var i = 0; i <= words.length - 1; i++) {
if (words[i] != " ") {
if (firstChar === 0) {
reversedWords[counter] = words[i];
firstChar++;
} else {
reversedWords[counter] += words[i];
}
} else {
firstChar = 0;
counter++;
}
}
reversedWords.forEach(word => reverseText.textContent += word + " ");
<p id="text">hello nixit
<p>
<p id="reverseText">
<p>

Related

Specific Array element replace

I'm solving a simple problem where I need to capitalize the first alphabet of all words. I was able to do that but I have another string vn52tqsd0e4a if any of my output is matched with this string I have to replace it with --[matched string]-- .
so the expected output should be H--e--llo Worl--d--
but when I'm trying to replace the element with -- it's not doing anything. I tried replace() method as well but it didn't work. I don't know what I'm doing wrong here.
function LetterCapitalize(str) {
// code goes here
let array = str.split(" ")
for (let i=0; i<array.length; i++){
array[i] = array[i].charAt(0).toUpperCase() + array[i].slice(1)
}
let output = array.join(" ") ;
let comp = "vn52tqsd0e4a".split("");
for (let i=0; i<output.length; i++){
comp.map(el=> {
if(output[i] === el){
console.log( `matched ${output[i]}` )
output[i] = `--${output[i]}--`;
console.log(output[i]);
}
})
//
}
console.log(output);
}
LetterCapitalize("hello world");
You can achieve this using split, map, join as:
function LetterCapitalize(str) {
// code goes here
let array = str.split(' ');
for (let i = 0; i < array.length; i++) {
array[i] = array[i].charAt(0).toUpperCase() + array[i].slice(1);
}
let output = array.join(' ');
let comp = 'vn52tqsd0e4a'.split('');
const result = output
.split('')
.map((c) => (comp.includes(c) ? `--${c}--` : c))
.join('');
console.log(result);
}
LetterCapitalize('hello world');
You coulduse Array.reduce() to iterate over the str argument and either capitalize or replace depending on the character.
If the preceeding value is a space we'll capitalize, otherwise if the character is in the comp value, we'll replace with --${char}--.
function LetterCapitalize(str) {
const comp = "vn52tqsd0e4a";
return [...str].reduce((acc, char, idx, a) => {
if (idx === 0 || a[idx - 1] === ' ') {
char = char.toUpperCase();
} else if (comp.includes(char)) {
char = `--${char}--`;
}
return acc + char;
}, '')
}
console.log(LetterCapitalize("hello world"));
console.log(LetterCapitalize("hey man"));
What you say to JavaScript in the piece of code is that it should fit 5 characters in a place that can only hold one character.
output[i] = `--${output[i]}--`;
You need to change it to something like this (code below may not work):
output = output.substring(0,i-1) + el + output.substring(i+1,output.length - i-1);
I recommend using the string.replaceAll function instead. If you create a loop yourself you'll get problems when adding more characters on a place where original one character was present.
function LetterCapitalize(str) {
// code goes here
let array = str.split(" ")
for (let i=0; i<array.length; i++){
array[i] = array[i].charAt(0).toUpperCase() + array[i].slice(1)
}
let output = array.join(" ") ;
let comp = "vn52tqsd0e4a".split("");
comp.map(el=> {
output = output.replaceAll(el, '--' + el + '--');
});
console.log(output);
}
LetterCapitalize("hello world");

How to make abbreviations/acronyms in JavaScript?

new to coding I'm trying to make a function that makes "abbreviations/acronyms" of words, e.g. 'I love you' -> 'ily'.
I've tried rewriting the code in many ways but console.log only shows me the first letter of the first given word.
function makeAbbr(words) {
let abbrev = words[0];
let after = 0;
let i = 0;
for (const letter of words) {
if (letter === '') {
i = words.indexOf('', after);
abbrev += words[i + 1];
}
after++;
}
return abbrev;
}
const words = 'a bc def';
let result = makeAbbr(words);
console.log(result)
Without using arrays. But you really should learn about them.
Start by trimming leading and trailing whitespace.
Add the first character to your acronym.
Loop over the rest of the string and add the current character to the acronym if the previous character was a space (and the current character isn't).
function makeAbbr(words) {
words = words.trim();
const length = words.length;
let acronym = words[0];
for(let i = 1; i < length; i++) {
if(words[i - 1] === ' ' && words[i] !== ' ') {
acronym += words[i];
}
}
return acronym;
}
console.log(makeAbbr('I love you'));
console.log(makeAbbr('I love you'));
console.log(makeAbbr(' I love you '));
And here's the version for GottZ
function w(char) {
char = char.toLocaleLowerCase();
const coll = Intl.Collator('en');
const cmpA = coll.compare(char, 'a');
const cmpZ = coll.compare(char, 'z');
return cmpA >= 0 && cmpZ <= 0;
}
function makeAbbr(words) {
words = words.trim();
const length = words.length;
if(!length) return '';
let acronym = words[0];
for(let i = 1; i < length; i++) {
if(!w(words[i - 1]) && w(words[i])) {
acronym += words[i];
}
}
return acronym;
}
console.log(makeAbbr('I love you'));
console.log(makeAbbr('I love you'));
console.log(makeAbbr(' I love you '));
console.log(makeAbbr(' \tI ... ! love \n\r .you '));
console.log(makeAbbr(' \tI ... ! Löve \n\r .ÿou '));
Since you wanted something using your approach, try this (code is commented)
function makeAbbr(words) {
let abbrev = "";
for (let i = 0; i < words.length - 1; i++) { // Loop through every character except the last one
if (i == 0 && words[i] != " ") { // Add the first character
abbrev += words[i];
} else if (words[i] == " " && words[i + 1] != " ") { // If current character is space and next character isn't
abbrev += words[i + 1];
}
}
return abbrev.toLowerCase();
}
const words = 'a bc def';
let result = makeAbbr(words);
console.log(result)
here is my implementation of your function:
Split the sentence into an array, get the first letter of each word and join them into one string.
const makeAbbr = string => string.split(' ').map(word => word[0]).join('');
console.log(makeAbbr('stack overflow'));
console.log(makeAbbr('i love you'));
`
If you want to use your approach exactly, you had a typo on the line specified. A character can never be "" (an empty string), but a character can be a space " ". Fixing this typo makes your solution work.
function makeAbbr(words) {
let abbrev = words[0];
let after = 0;
let i = 0;
for (const letter of words) {
if (letter === ' ') { // This line here
i = words.indexOf(' ', after);
abbrev += words[i + 1];
}
after++;
}
return abbrev.toLowerCase(); // Also added .toLowerCase()
}
const words = 'a bc def';
let result = makeAbbr(words);
console.log(result)
There are couple of things tripping you up.
let abbrev = words[0]; is just taking the first letter of the word string you passed into the function, and at some point adding something new to it.
for (const letter of words) {...}: for/of statements are used for iterating over arrays, not strings.
Here's a remixed version of your code. It still uses for/of but this time we're creating an array of words from the string and iterating over that instead.
function makeAbbr(str) {
// Initialise `abbrev`
let abbrev = '';
// `split` the string into an array of words
// using a space as the delimiter
const words = str.split(' ');
// Now we can use `for/of` to iterate
// over the array of words
for (const word of words) {
// Now concatenate the lowercase first
// letter of each word to `abbrev`
abbrev += word[0].toLowerCase();
}
return abbrev;
}
console.log(makeAbbr('I love you'));
console.log(makeAbbr('One Two Three Four Five'));

How to find the longest sequence of "broken" characters using Regex in JS?

I'm trying to find the longest sequence of "broken"(different from letter, digit, space) characters in this sentence:
'Tempera####&&#^ na ##$ata 23 grad#%&.'
I really want to do it using Regex, but I'm not that familiar with the usage of Regex in JS. This is the description of the problem: https://pastebin.com/U6Uukc4b
I watched a lot of tutorials, also read bunch of articles and this is what I came up with:
let input = [
'Tempera####&&#^ na ##$ata 23 grad#%&.'
];
let print = this.print || console.log;
let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
let message = gets();
//different from letter, digit, space
let counter = 1;
let allWords = /[a-z1-9\s]/gi;
for (let i = 0; i < message.length; i++) {
let current = message[i];
// allWords.lastIndex = 0;
let isExisting = allWords.test(current);
if (current === '.') {
break;
}
if (isExisting) {
counter = 1;
} else {
counter++;
}
}
print(counter)
Here the answer should be 8 , because we have 8 consecutive symbols inside the word "Tempera####&&#^" , which are not letter, digit or space.
Unfortunately this doesn't work. I'm still trying to understand where is my mistake, so I'll be very thankful if someone can "show me the way".
Use a regular expression that matches the opposite ([^.....]) and as many times as possible (+). Then check the size of all matches and pick the longest length. As there is a special role for the point (which apparently is always at the end), consider it as not broken.
let allWords = /[^a-z1-9\s.]+/gi;
let input = [
'Tempera####&&#^ na ##$ata 23 grad#%&.'
];
for (let message of input) {
let results = message.match(allWords) ?? [];
let counter = Math.max(0, ...results.map(({length}) => length));
console.log("longest", counter);
}
const input = 'Tempera####&&#^ na ##$ata 23 grad#%&.';
function findLongestSubstring(input) {
let longest = '';
let current = '';
for (let i = 0; i < input.length; i++) {
if (input[i].match(/[^a-zA-Z\d\s]/)) {
current += input[i];
} else {
if (current.length > longest.length) {
longest = current;
}
current = '';
}
}
return longest.length;
}
console.log(findLongestSubstring(input));

Why won't this iterate?

I am trying to make this Pig Latin function (I just started coding 3 weeks ago, so go easy on me), and I can't figure out why I can't get the array made from .split(' ') and then iterated through to join back again. In the output I only get the first word. The code is below:
function pigLatin(str) {
let str1 = str.split(' ')
for (let i = 0; i < str1.length; i++) {
if (str1[i].length <= 1) {
return str1[i];
}
else {
let first = str1[i].substring(0,1);
let word = str1[i].substring(1);
str = word + first + 'ay';
return str
}
}
}
console.log(pigLatin("This is a test"));
Keep in mind that I was considering adding regex and more else if statements, but I can't even get this to work yet. Any help is greatly appreciated.
You're returning too early. You should be adding each word to an array, and at the end of your loop you should concatenate the words in the array to form a new string which you should return. See my comments for how I altered your code:
function pigLatin(str) {
let r = [] // The array to build
let str1 = str.split(' ')
for (let i = 0; i < str1.length; i++) {
if (str1[i].length <= 1) {
r.push( str1[i] ); // Add to end of array
}
else {
let first = str1[i].substring(0,1);
let word = str1[i].substring(1);
str = word + first + 'ay';
r.push(str) // Add to end of array
}
}
return r.join(' ') // Join strings in array and return new string
}
console.log(pigLatin("This is a test"));

Word count is incorrect when multiple spaces are present in the string

This function works fine.
But if i add more spaces in str than it gives the wrong count of words. Any help would be appreciated.
str = "coune me in"
var obj = {};
var regex = /[\s]/gi
function count(str){
// total spaces in a string
var spacesCount = str.match(regex).length;
// words count
var wordsCount = str.split(' ').length;
//charetcers count
var charsCount = str.split('').join('').length;
//average count
var avgCount = str.split(' ').join('').length/wordsCount;
// adding it to the object
obj.words = wordsCount;
obj.chars = charsCount;
obj.avgLength = avgCount;
obj.spaces = spacesCount;
return obj
}
count(str)
Try something like:
mystring.split(/\s+/);
This will split on one or more white-space characters so two spaces (or more) in a row will be treated as just one split.
let Allah = 'Allah is our creator.'
Allah = Allah.trim();
count = 0;
for (let i = 0; i < Allah.length; i++) {
let char = Allah[i];
if (char == " " && Allah[i-1] != " ") {//add here
count++;
}
}
count++;
console.log(count);
//output:4

Categories