Getting an array with lengths of words from a sentence -javascript - javascript

I'm trying to create a function that will tell me how long the longest word in a sentence is. My approach is to split the sentence into strings of words. I now have an array of strings. My problem is that I want to use this array to get another array of numbers i.e. the length of each word. How do I do this? My code is as below but I keep getting null.
function findLongestWord(str) {
var split = str.split(" ");
for (j = 0; j < split.length; j++)
var wordCount = split[j].length;
var lengths = [];
for (var i = 0; i < wordCount.length; i++) {
lengths.push(i);
}
return Math.max(...lengths);
}

If you are going to loop through all the words you can already find the max (longest) word in your input array.
function findLongestWord(str) {
var split = str.split(" ");
var maxLength = 0;
var longestWord = ""; // If no word is found "".length will return 0
var len = split.length;
for (j = 0; j < len; j++)
{
if (split[j].length > maxLength)
{
longestWord = split[j];
maxLength = split[j].length;
}
}
return longestWord;
}
And the returned value .length to get the length (or return maxLength if you so desire).
Note depending on your application punctuation might interfere with your algorithm.

I've made some comments about the mistakes in your code
function findLongestWord(str) {
// better use .split(/\s+/) instead to remove trailing space in the middle of sentence
var split = str.split(" ");
// this for loop is redundant, you have to wrap the code that you want to loop with curly brackets.
for (j = 0; j < split.length; j++)
// the value of j would be the length of split array.
var wordCount = split[j].length;
var lengths = [];
// since wordCount.length is undefined, so loop never gets excuted and your lengths array would be empty.
for (var i = 0; i < wordCount.length; i++) {
lengths.push(i);
}
// doing Math.max on empty array will return -Infinity
return Math.max(...lengths);
}
findLongestWord('hello there mate')
Below are my solutions. There are also more ways of doing what you want to do.
function findLongestWord(str) {
// trim trailing white space.
var split = str.trim().split(/\s+/);
var lengths = [];
// loop through array of words
for (j = 0; j < split.length; j++) {
// check the length of current words
var wordCount = split[j].length;
lengths.push(wordCount);
}
return Math.max(...lengths);
}
const sentence = 'hello its a me mariooooooo';
console.log(findLongestWord(sentence))
// one liner - using reduce function
const findLongestWord2 = (str) => str.trim().split(/\s+/).reduce((a, b) => a.length > b.length ? a.length : b.length, -Infinity);
console.log(findLongestWord2(sentence))
// less efficient but shorter - using sort
const findLongestWord3 = (str) => str.trim().split(/\s+/).sort((a, b) => a.length - b.length).pop().length;
console.log(findLongestWord3(sentence))

Create a function that takes an array of words and transforms it into an array of each word's length.
function multi(arr) {
var newarr = [];
for (var i = 0; i < arr.length; i++) {
newarr.push( arr[i].length);
}
return newarr;
}

You need to use var to create j in the first for loop like you did for the second for loop with i.

This can be done using the .map() method. You map the array of strings into an array of word lengths, and then return the Math.max() of the array of lengths, like so:
function findLongestWord(str) {
// map words into array of each word's length, grab highest #
return Math.max(...str.split(" ").map(str => str.length));
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));

Related

Why aren't my nested array elements being added together properly?

Why I am getting this kinda error. But when I am calculating products of them, they seem fine.
//The funtion will add all the values in that array....
function addArrayValues(arr) {
var addition = 0;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
addition += arr[i][j];
}
}
return addition;
}
var addition = addArrayValues([[[23], [34], [54]], [[34], [75]], [[75]], [65]]);
console.log(addition);
You don't have an array of arrays - rather, you have an array of arrays of arrays. You need to go 3 levels deep, not just 2:
//The funtion will add all the values in that array....
function addArrayValues(arr){
var addition=0;
for(var i=0;i<arr.length;i++){
for(var j=0;j<arr[i].length;j++){
for (var k = 0; k < arr[i][j].length; k++) {
addition+=arr[i][j][k];
}
}
}
return addition;
}
var addition=addArrayValues([[[23],[34],[54]],[[34],[75]],[[75]],[65]]);
console.log(addition);
Or use .flat instead:
//The funtion will add all the values in that array....
const addArrayValues = arr => arr
.flat(2)
.reduce((a, b) => a + b, 0);
var addition=addArrayValues([[[23],[34],[54]],[[34],[75]],[[75]],[65]]);
console.log(addition);
Your original code is implicitly coercing the 3-deep arrays to strings first, so, eg, iterating over
[[23],[34],[54]]
starts by calculating
[23] + [34] + [54]
so the arrays are turned to strings during the creation of the addition variable.

JavaScript - Find a word string out of strings in a two dimensional array

I am trying to find a word from consecutive strings inside a two dimensional array.
For example:
array = [[0,'r',0,0,0,0,0],
[0,'a',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'l',0,0,0,0,0],
[0,'e',0,0,0,0,0]];
I want to make a function that will return true if the word 'apple' is inside this array vertically. Strings need to be consecutive.
Or:
array1 = [[0,'e',0,0,0,0,0],
[0,'l',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'a',0,0,0,0,0],
[0,'q',0,0,0,0,0]];
It should work from top to bottom and from bottom to top.
This should return false since there are no consecutive letters:
array2 = [[0,'e',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'l',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'a',0,0,0,0,0],
[0,'q',0,0,0,0,0]];
Can you help please?
Here's a function that does exactly what you need:
let array1 = [
[0,'r',0,0,0,0,0],
[0,'a',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'l',0,0,0,0,0],
[0,'e',0,0,0,0,0]
];
let array2 = [
[0,'r',0,0,0,0,0],
[0,'e',0,0,0,0,0],
[0,'l',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'a',0,0,0,0,0]
];
function includesWordVertically(matrix, word) {
for (let j = 0 ; j < matrix[0].length ; j++) {
let verticalWord = '';
for (let i = 0 ; i < matrix.length ; i++) {
verticalWord += matrix[i][j];
}
if ((verticalWord.includes(word)) ||
(verticalWord.split('').reverse().join('').includes(word)))
{
return true;
}
}
return false;
}
console.log(includesWordVertically(array1, 'apple'));
// true
console.log(includesWordVertically(array2, 'apple'));
// true
Note that this function does not do the necessary checks (e.g. matrix not empty, all rows have the same length, etc).
I would combine a single string from all characters in one vertical column, and also add another set of same characters, so if the word Apple is divided, you will fins it is a string. After adding all characters twice, you will get a string like 'leappleapp' and you will find an apple there
Returns true Only if found in a straight column.
var array1 = [[0,'a',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'p',0,0,0,0,0],
[0,'l',0,0,0,0,0],
[0,'e',0,0,0,0,0],
[0,'q',0,0,0,0,0]];
function isVertically(array, word) {
var string = "";
var index = -1;
for(var i = 0; i < array.length; i++) {
var line = array[i];
for(var j = 0; j < array.length; j++) {
var element = line[j];
if(typeof element == "string") {
if(index < 0)
index = j;
if(j === index)
string += element;
}
}
}
return string == word;
}
isVertically(array1, "apple")

Ho to reverse split string into a JavaScript array?

I want to use one loop to split or explode a string into an array like
"Work" // -> var strArray = [k, rk, ork, work]
I tried for loop, but I know this is not an efficient.
for (let index = 0; index < word.length; index++)
{
strArray.push(word[word.length - 1]);
}
Any idea?
It looks like you may want to be sliceing your string. Here's something that'll do that:
function wordSplit(word) {
let strArray = [];
for (let i = 0; i < word.length; i++) {
strArray.push(word.slice(i));
}
return strArray;
}
And a fiddle: https://jsfiddle.net/13kephm9/7/
You can split the string, and iterate the array with Array#map, and generate the string using slice:
var word = 'work';
var result = word.split('').map(function(l, i) {
return word.slice(-i - 1);
});
console.log(result);
for (let index = 0; index < word.length; index++)
{
strArray.push(word.slice(index));
}
array string elements reversing
function rev(arr){
var text = new Array;
for(var i= arr.length-1;i>= 0;i--){
text.push(arr[i]);
}
return text.join();
}
console.log(rev(["a","b","c"]));
`print`

How to take First letter from the string with comma separated?

I have one array and I store comma separated strings in the array. Now I want to take in the string every first letter take from the string with comma separated.
For ex => Abc, Xyz, Hji so now I want A, X, H.
Here below listed my code and array.
This is my code =>
var ArryString = [];
for (var i = 0; i < data.length; i++) {
ArryString.push(data[i].Str);
}
Current o/p =>
"Abc"
"Xyz,Hji,Lol",
"Uyi,Mno"
my expacted o/p= >
"A"
"X,H,L"
"U,M"
You could split the strings and take only the first character with a destructuring assignment and join the first characters for a string. Then map the new string for a new array.
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
result = data.map(s => s
.split(',')
.map(([c]) => c)
.join());
console.log(result);
This is not looking good and amateurish but understandable.
var ArryString = [];
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
var index=0;
for (var k in data){
var a=data[k].split(",");
ArryString[index]=a[0].charAt(0);
if(a.length > 1)
for (var l=1 ;l<a.length ; l++)
ArryString[index]+=","+a[l].charAt(0);
index++;
}
console.log(ArryString);
You can use charAt method Return the first character of a string.
var newString = [];
for (var i=0; i< newString.length; i++)
{
newString.push(ArrayString[i].charAt(0);
}
Here is a working example :
// We've got an array of comma separated worlds
// Sometimes we've got one, sometimes several
data=["Hello","i","have","one,array","and,i","store","comma,separated,string,in","the","array"];
// We want to ouput the same pattern but keeping the initial letter only
var result = [];
var items = [];
var aChar;
// We loop thru the data array
for (var i = 0; i < data.length; i++) {
// We make a small array with the content of each cell
items = data[i].split(",");
for (var j = 0; j < items.length; j++) { // We loop thru the items array
aChar = items[j].charAt(0); // We take the first letter only
if (aChar!="") // If the item/work was not empty the we keep only the initial letter in our items array
items[j] = aChar;
}
result.push(items.join(",")); // we store comma separated first letters in our result array
}
console.log(result)
Use the String.charAt() method for each string in the array and push the first character to a new array.
Example function:-
function takeFirstChar(arr){
var new_arr = [];
arr.forEach(function(el){
var firstLetter = el.charAt(0)
new_arr.push(firstLetter);
});
return new_arr;
}
takeFirstChar(['hello','cruel','world']);
//Output-> ['h','c','w']

replace all vowels in a string javascript

I am trying to write a function that will remove all vowels in a given string in JS. I understand that I can just write string.replace(/[aeiou]/gi,"") but I am trying to complete it a different way...this is what I have so far... thank you!
I first made a different function called IsaVowel that will return the character if it is a vowel...
function withoutVowels(string) {
var withoutVowels = "";
for (var i = 0; i < string.length; i++) {
if (isaVowel(string[i])) {
***not sure what to put here to remove vowels***
}
}
return withoutVowels;
}
Use accumulator pattern.
function withoutVowels(string) {
var withoutVowels = "";
for (var i = 0; i < string.length; i++) {
if (!isVowel(string[i])) {
withoutVowels += string[i];
}
}
return withoutVowels;
}
function isVowel(char) {
return 'aeiou'.includes(char);
}
console.log(withoutVowels('Hello World!'));
I tried doing this problem by first splitting the string into an array, while also creating an array of vowels. Then go through each element in the string array and check whether it's in my vowel array. If it is not in my vowel array, push it to the withoutVowels array. At the end of the for loop, join all elements in the withoutvowels array and return.
function withoutVowels(string) {
var strWithoutVowels = [];
string = string.split('');
var vowels = ['a', 'e', 'i', 'o', 'u'];
for (var i = 0; i < string.length; i++) {
if (vowels.indexOf(string[i]) < 0) {
strWithoutVowels.push(string[i])
}
}
strWithoutVowels = strWithoutVowels.join('');
return strWithoutVowels;
}
console.log(withoutVowels('Hello World!'))
I think the easiest way is to use a regex; it's cleaner and faster compared to all your loops. Below is the code.
string.replace(/[aeiou]/gi, '');
the gi in the code means no matter the case whether uppercase or lowercase so long as its a vowel, it will be removed

Categories