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

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

Related

Javascript-Arrays: Get the index of the first item, that begins with a letter

Lets say i have the following array:
['1', '1/2', 'fresh', 'tomatoes']
how can i get the index of the first item, that beginns with a letter, in this case "fresh"?
Please note that it should work with every letter, not just with a specific one.
Thanks.
An alternative is using the function findIndex along with a regex to check the first char.
Assuming every string has at least one char.
let arr = ['1', '1/2', 'fresh', 'tomatoes'],
index = arr.findIndex(s => /[a-z]/i.test(s[0]));
console.log(index);
Using regex, you can use /[a-zA-z]/ (which matches the first letter in a string) together with search(), for every array item using a for loop, and when search(/[a-zA-Z]/) returns 0, stop and return the current index.
var arr = ['1', '1/2', 'fresh', 'tomatoes'];
for(var i = 0; i < arr.length; i++) {
if(arr[i].search(/[a-zA-Z]/) == 0) {
console.log(i);
break;
}
}
Here is another solution, this time using character codes:
var arr = ['1', '1/2', 'fresh', 'tomatoes'];
for(var i = 0; i < arr.length; i++) {
var x = arr[i][0].charCodeAt();
if((x >= 65 && x <= 90) || (x >= 97 && x <= 122)) {
console.log(i);
break;
}
}
My suggestion:
function myFunction() {
var i;
var str = ['1', '1/2', 'fresh', 'tomatoes'];
for(i=0; i<str.length; i++){
if (str[i].charAt(0) >= 'a' && str[i].charAt(0) <= 'z') {
console.log(i);
break;
}
}
}

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 get even numbers array to print first instead of odds?

So I have this function where I've need to take out the evens and odds and put them into separate arrays but I need the evens array to print first rather than the odds.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[i & 1].push(numbersArray[i]);
}
return evensOdds;
}
If you want to split the number by their even and odd values, instead of using the index (i), determine the sub array to push into using the value - numbersArray[i] % 2.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[numbersArray[i] % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
If you want to split them by even and odd indexes use (i + 1) % 2 to determine the sub array to push into:
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[(i + 1) % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
Just for fun, a forEach version of the accepted answer.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var even_odd = [ [], [] ];
numbersArray.forEach( e => even_odd[e%2].push(e) );
console.log(even_odd);

Getting an array with lengths of words from a sentence -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"));

Why does this .indexOf method not work on this array?

I have the following code:
var newArr = [];
function mutation(arr) {
//Makes both values lowercase
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i].toLowerCase());
}
//splits the letters of the second value into separate values.
var letters = [];
letters.push(newArr[1]);
letters = letters.toString();
letters = letters.split('');
//checks to see if there is a letter that isn't in the first value.
for (var j = 0; j < letters.length; j++) {
if (newArr[1].indexOf(letters[j]) == -1) {
return false;
}
}
return true;
}
mutation(["voodoo", "no"]);
It works on something like (["hello", "hey"]), but it doesn't work on the method above. Why does the .indexOf method not work on this array?
I dont really know what the code should do but lets check it step by step:
var newArr = [];
function mutation(arr) {
// Makes both values lowercase
// arr is now ["voodoo", "no"]
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i].toLowerCase());
}
// newArr has the same content: ["voodoo", "no"]
//splits the letters of the second value into separate values.
var letters = [];
letters.push(newArr[1]); // letters is now ["no"]
letters = letters.toString(); // letters is now "no"
letters = letters.split(''); // letters is now ["n", "o"]
//checks to see if there is a letter that isn't in the first value.
for (var j = 0; j < letters.length; j++) { // foreach ["n", "o"]
if (newArr[1].indexOf(letters[j]) == -1) { // "no".indexOf("n") and "no".indexOf("o") is always > -1
return false; // so false is never returned
}
}
return true; // true is always returned
}
mutation(["voodoo", "no"]);
I think you should change the
if (newArr[1].indexOf(letters[j]) == -1)
to
if (newArr[0].indexOf(letters[j]) == -1)
if you want to test if one letter of the second word is not included in the first word.

Categories