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

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

Related

How can I find all first indexes of sequence of consecutive zeroes in an array?

I am trying to push all first indexes that point to a start of a sequence of consecutive 0s from the array A into a new array arr.
var C determines the amount of 0s in the sequence. For example, if C is 2, the algorithm will look for 00s, if C is 3 it will look for 000s and so on. N is the length of an array A. The algorithm seems to work, but for some reason the values in the new array arr are duplicated
var A = [1, 0, 0, 1];
var N = 4;
var C = 1;
function S(A, N, C) {
var arr = [];
for (var i = 0; i < N; i++) {
for (var j = 0; j <= C; j++) {
if ((A[i] == 0) && (A[i + j] == 0)) {
arr.push(i);
}
}
}
console.log(arr);
return -1;
}
/// console result:
Array(5)
0: 1
1: 1
2: 2
3: 2
//Expected:
0: 1
1: 2
First I would like to recommend that you use more descriptive variable names. The fact that you need to describe what each of them means, means that they are not descriptive enough.
Also your variable N seems redundant, because arrays already have a .length property that you can use to see how many elements are in there.
The source of your error seems to be that you use a nested loop. There is no need to use nested loops. You only need to go through all elements once and keep track of the repeated zeroes. Every time you encounter a non-zero value, you reset the sequence count to 0. If do encounter a zero you increment the sequence count and afterwards you check if the sequence count is equal to the number of zeroes you passed as an argument. In that case you want to push the first index to the resulting array and reset the sequence count to 0 again.
function getFirstIndexesOfSequenceOfConsecutiveZeroes(input, numberOfRepeatedZeroes) {
if (numberOfRepeatedZeroes <= 0) {
throw new Error("numberOfRepeatedZeroes need to be 1 or higher");
}
var firstIndexes = [];
let sequenceStartIndex;
let sequenceCount = 0;
for (var i = 0; i < input.length; i++) {
if (input[i] !== 0) {
sequenceCount = 0;
} else {
if (sequenceCount == 0) {
sequenceStartIndex = i;
}
sequenceCount++;
}
if (sequenceCount === numberOfRepeatedZeroes) {
firstIndexes.push(sequenceStartIndex);
sequenceCount = 0;
}
}
return firstIndexes;
}
let input = [1, 0, 0, 1];
let numberOfRepeatedZeroes = 1;
console.log(getFirstIndexesOfSequenceOfConsecutiveZeroes(input, numberOfRepeatedZeroes));
Try:
function S(A, B, C) {
var arr = [];
for (var i = 0; i < B; i++) {
for (var j = 0; j <= C; j++) {
if ((A[i] == 0) && (A[i + j] == 0) && !arr.includes(i)) {
arr.push(i);
}
}
}
console.log(arr);
return -1;
}
With this simple add in the if, you check if the value is already in your array.

Trying to remove duplicate elements with the same values that are next to each other in an array (they have to preserve the original order)

So). This removes all duplicates. But I cann't figure out the logic for removing duplicates that are next to each other only.
For example:
input:('FFNNbbffnnNN');
output:[F, N, b, f, n, N];
var uniqueInOrder = function(iterable){
var newArr =[];
var len = iterable.length;
for(var i = 0; i < len ; i ++){
if( newArr.indexOf(iterable[i]) === -1){
newArr.push(iterable[i])
}
}
return newArr;
}
uniqueInOrder('ffssSnnsS');
Here I tried a little bit.. meh.. begging for tips. Thank you!
var uniqueInOrder = function(iterable){
var newArr =[];
var len = iterable.length;
var first = iterable[0];
for(var i = 0; i < len ; i ++){
if( newArr.indexOf(first) !== newArr.indexOf(first + 1){
newArr.push(iterable[i])
}
}
return newArr;
}
uniqueInOrder('ffssSnnsS');
Better to remove from backward to avoid miss splice when there are more than two duplicate elements after iteration took place:
var nums = [1,2,3,3,4,5,5,6,7,7,7,8];
for (i=nums.length-1; i > 0; i--) {
if(i <= nums.length && nums[i] === nums[i - 1]){
nums.splice(i,1);
}
}
console.log(nums);
Use Array.filter().
var nums = [1,2,3,3,4,5,5,6,7,7,8];
nums.forEach(function(num,index){
// Is the current index < the amount of itmes in the array
// and, if so, is the current item equal to the next item?
if(index < nums.length && num === nums[index + 1]){
nums.splice(index,1); // Remove the current item
}
});
console.log(nums);
I did it like this:
function uniqueInOrder(str) {
const letters = str.split('');
var lastLetter = null;
for (let [index,letter] of Object.entries(letters)) {
if (letter === lastLetter) {
letters[index] = null;
} else {
lastLetter = letter;
}
}
console.log(letters);
return letters.join('');
}
uniqueInOrder('ffssSnnsS');
I use split to turn it into an array. I keep track of the most recent previous letter. If the current letter matches, i null it in the array, otherwise i just update the lastLetter variable.

Skip numbers that include certain number in an array

I'm trying to create a function which takes 3 parameters – start, end and bannedNumber. It should print all the numbers from start to end but skip all multiples of the banned number and any number that has a banned number in it.
Here is my code:
<script>
var arr = [];
var str = "";
var newarr = [];
var str1
function Zumbaniaa(a, b, c) {
for (var i = a; i < b; i++) {
arr.push(i);
}
for (var j = 0; j < arr.length; j++) {
if (arr[j] % c == 0) {
arr.splice(j, 1);
}
}
for (var m = 0; m < arr.length; m++) {
str = arr[m].toString();
str1=str.split("");
if (str1.indexOf(c) >=0) {
arr.splice(m, 1);
}
}
return arr
}
document.write(Zumbaniaa(1, 90, 8))
console.log(str1)
</script>
For some reason the third loop is not working. It's not filtering numbers with 8 at all.
It's simplest to just not push the banned values into the array to begin with. So check if the numbers to be pushed are a multiple of the banned digit, or contain the banned digit before you push:
function filtered_range(start, end, banned) {
let nums = [];
for (let i = start; i <= end; i++) {
if (i % banned != 0 && i.toString().indexOf(banned) == -1) nums.push(i);
}
return nums;
}
console.log(filtered_range(1, 90, 8).join(' '));
Remove this line: str1 = str.split("");. It is causing indexOf() to fail. Call str.indexOf(c) instead. Then reverse the final loop.
What is happening: indexOf() works on strings and arrays. When used on a string, the character being searched for is always parsed first to a string, because strings only contain strings. When used on an array, the character being searched for isn't parsed at all, because arrays can contain strings, numbers, etc.
var arr = [];
var str = "";
var newarr = [];
var str1
function Zumbaniaa(a, b, c) {
for (var i = a; i < b; i++) {
arr.push(i);
}
for (var j = 0; j < arr.length; j++) {
if (arr[j] % c == 0) {
arr.splice(j, 1);
}
}
for (var m = arr.length - 1; m > 0; m--) {
str = arr[m].toString();
//str1 = str.split("");
if (str.indexOf(c) >= 0) {
arr.splice(m, 1);
}
}
return arr
}
Zumbaniaa(1, 90, 8);
console.log(arr);

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

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