Finding double vowels in Array Javascript - javascript

const gotCitiesCSV =
"King's Landing,Braavos,Volantis,Old Valyria,Free Cities,Qarth,Meereen";
let returnOnly = gotCitiesCSV => Array.from(gotCitiesCSV).filter(letter =>
'aa','ee','ii','oo','uu'.includes(letter)).length;
let callElement = document.createElement("div");
callElement.textContent = JSON.stringify(returnOnly)
document.getElementById('kata23').appendChild(callElement)
return returnOnly;
}
When i try to run my code nothing is returning. So not sure if i am not calling the double vowels correctly. Trying to return the items that has double vowels and as well return as an array instead of a string.

Looks like there is a few things going on in that example, but i took a stab at creating a working solution for ya with explanations about whats going on
const gotCitiesCSV =
"King's Landing,Braavos,Volantis,Old Valyria,Free Cities,Qarth,Meereen";
// 1. Array.from() wont split the list of cities into an array
const gotCities = gotCitiesCSV.split(',');
// 2. `returnOnly` is a function, not a result. it looks like you want it to be the result;
const doubleVowels = ['aa','ee','ii','oo','uu'];
const doubleVowelCities = gotCities.filter(
// filter in the cities which
cityName => doubleVowels.some(
// contain some double vowel (i.e., atleast one)
doubleVowel => cityName.includes(doubleVowel),
),
)
which returns
> console.log(doubleVowelCities);
[ 'Braavos', 'Free Cities', 'Meereen' ]

Seems you were nearly there but your logic was a bit wrong. You need to use split to break cities from comma and check each individual one against the vowels you have.
Need to use includes on each string found in filter function so that it can checked if they vowels.
Live Demo:
const gotCitiesCSV = "King's Landing,Braavos,Volantis,Old Valyria,Free Cities,Qarth,Meereen";
let splitStr = gotCitiesCSV.split(',') //split in commas
splitStr.filter(function(x) {
if (x.includes('aa') || x.includes("ee") || x.includes('ii') || x.includes('oo') || x.includes('uu')) {
let callElement = document.createElement("div");
callElement.textContent = JSON.stringify(x)
document.getElementById('kata23').appendChild(callElement)
}
})
<div id="kata23"></div>

Related

How to Add Default Elements to an Array when Requirements Not Met?

I have a code that converts user input to an array then does a fetch request. The rest of the code only works when the array has a quantity (as a string) and a unit (as a string). So for example, it works when I type in "1 whole apple" or "1 oz chicken thigh" but it breaks when it's just "apple". How can I set up a checkpoint to add "1" and "whole" to the beginning of the array when quantity and unit are missing?
const [input, setInput] = useState("")
const foodName = []
const searchArray = []
// This part below separates user input by space then forms an array
const inputArray = input.split(/(\s+)/).filter(e => String(e).trim())
// This part below forms a new array with only the quantity and the unit, or nested arrays if the user inputs more than one item, which obviously breaks if there is no quantity.
const array = inputArray.reduce(
(arrays, value) => (
isFinite(value)
? arrays.push([value])
: arrays[arrays.length - 1].push(value),
arrays
),
[]
)
// This part below combines food name to a single element if it has more than one word i.e. apple pie.
for (var i = 0; i < array.length; i++) {
const foodName = array[i].splice(2).join(' ')
foodArray.push(foodName)
const wholeArray = array[i].concat(foodArray[i])
searchArray.push(wholeArray)
}
Making the fetch request etc.
Thanks in advance!
So I ended up adding an error message since I could not find a solution to this.
if (!isFinite(inputArray[0])) {
setErrorMessage('Be sure to specify quantity and unit!')
return
}
const array = inputArray.reduce(
(arrays, value) => (
isFinite(value)
? arrays.push([value])
: arrays[arrays.length - 1].push(value),
arrays
),
[]
)

How to search for multiple words on a HTML page using JavaScript?

Right now my code is looking for the words 'Cheese' or 'Bread' within a specific webpage, and if it finds either word it should display an alert. However, it only displays the alert if the first word is found (cheese). Any suggestions on how to fix it so that it will successfully look for more than one word?
var array = Array.from(document.getElementsByClassName('wide-content-host'))
.find(el => el.innerText.includes('Cheese', 'Bread'));
if (array){
alert("Word found!")
}
This is an obvious change, but we could put an OR operator inside of the statement to signify both of them, like so:
let array = Array.from(document.getElementsByClassName('wide-content-host'))
.find(el => el.innerText.includes('Cheese') || el.innerText.includes('Bread'));
if (array) alert('Word found!');
You could also do it a more elegant way, like so:
const conditions = ['Cheese', 'Bread'];
const array = Array.from(document.getElementsByClassName('wide-content-host'));
const results = array.find((el) => conditions.some(nEl => el.innerText.includes(nEl)));
if (results) alert('Word found!');
This one works by grabbing the array from the 'wide-content-host' class name, then looping through that array with another loop that is looping through the values of the conditions array. With all of these loops working together, it will check whether or not the elements include the conditions.
** Edit **
In order to make the methods work without case-sensitivity, you would need to make the search cases lowercase e.g. 'cheese' and 'bread', and you would need to make the strings that you are searching through completely lowercase also.
Here are the examples for case-insensitivity:
let array = Array.from(document.getElementsByClassName('wide-content-host'))
.find(el => el.innerText.toLowerCase().includes('Cheese') || el.innerText.toLowerCase().includes('Bread'));
if (array) alert('Word found!');
or
const conditions = ['cheese', 'bread'];
const array = Array.from(document.getElementsByClassName('wide-content-host'));
const results = array.find((el) => conditions.some(nEl => el.innerText.toLowerCase().includes(nEl)));
if (results) alert('Word found!');
This can be done with regular expressions
let elem = document.querySelector("section");
let entries = elem.innerHTML.match(/(cheese)|(bread)/gi);
if (entries.length > 0) {
alert(`Words were found: ${entries}`);
}
<section>
<p>Cheese Bread</p>
<p>cheeSE BREAD</p>
</section>

How do I use javascript includes to filter out text that does not include specific text

I have a method that gets a list of saved photos and determines the number of photos listed. What I wish to do is return the number of photos that contain the text "Biological Hazards" in the name. Here is my code so far
getPhotoNumber(): void {
this.storage.get(this.formID+"_photos").then((val) => {
this.photoResults = JSON.parse(val);
console.log("photoResults", this.photoResults);
// photoResults returns 3 photos
// Hazardscamera_11576868238023.jpg,
// Biological Hazardscamera_11576868238023.jpg,
// Biological Hazardscamera_11576868351915.jpg
this.photoList = this.photoResults.length;
console.log("photoList", this.photoList); // returns 3
this.photoListTwo = this.photoResults.includes('Biological Hazards').length; // I wish to return 2
}).catch(err => {
this.photoList = 0;
});
}
Any help would be greatly appreciated.
Xcode log
[
One way to do this is to .filter() the array, and then calculate the length of that array.
this.photoListTwo = this.photoResults.filter(photoString => {
return photoString === 'Biological Hazards' //or whatever comparison makes sense for your data
}).length;
Quick solution for this (sorry for the lack of better formating, posting from mobile):
const array = ["Hazardscamera_11576868238023.jpg", "Biological Hazardscamera_11576868238023.jpg", "Biological Hazardscamera_11576868351915.jpg"];
const filterBioHazards = (str) => /Biological Hazards/.test(str);
console.log(array.filter(filterBioHazards).length);
// Prints 2
The method includes returns boolean to indicate whether the array contains a value or not. What you need is to filter your array and return its length after.
You need to replace the line:
this.photoListTwo = this.photoResults.includes('Biological Hazards').length;
By this:
this.photoListTwo = this.photoResults.filter(function(result) {return result.contains("Biological Hazards");}).length;

Get total values of unique items in react

I can get my tags. i.e., Pitcher, Pitcher, Catcher, Batter
I can get the unique ones. i.e., Pitcher, Catcher, Batter
How do I get?
Pitcher - 2
Batter - 1
Catcher - 1
const tags = attendance.map((entry) => entry.get('Tags')) // get tags
const uniqueTags = tags.filter((item, index) => tags.indexOf(item) === index) // get unique tags
Assuming tags ends up being ["Pitcher","Pitcher","Catcher","Batter"];
const tags = ["Pitcher","Pitcher","Catcher","Batter"];
const result = Object.entries(tags.reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(result);
Of course, as you can't see the exact content of tags the way you are using it, it may well be that tags is more like
const tags = ["","Pitcher","","Pitcher","","Catcher","","Batter"];
const result = Object.entries(tags.reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(tags.join('')); // you can't see the empty tags here
console.log(result); // but this is the result
This is why I asked you to post what attendance is, to see what is happening with the data
But, with filter as I suggested ...
const tags = ["","Pitcher","","Pitcher","","Catcher","","Batter"];
const result = Object.entries(tags.filter(t=>t).reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(tags.join('')); // you can't see the empty tags here
console.log(result); // with filter, everything is good again
If tags is an array of string (tags names), then you can use reduce to derive the desire output.
Example
var tags = ['Pitcher', 'Pitcher', 'Catcher', 'Batter', 'Batter'];
var result = tags.reduce((acc, val) => {
acc[val] = acc[val] || 0;
acc[val] = acc[val] + 1;
return acc;
}, {});
console.log(result);
Hope this will help!
Edit
To convert the final object into an array of string, you can use .map
Object.entries(result).map(([k, v]) => `${k}-${v}`);
Thanks for the heads up Jaromanda X

ReactJS / ES6: Searching Japanese text using includes?

So, I'm writing a client-side search and I need to look through strings of Japanese characters. I'm wondering how to do this properly?... i.e. Do I change the format of the text into utf-8 something and then search the utf-8?
Example:
All my data has japaneseData.title : "フェリーチェ三田"
When I type in my search.value as : "フェ" using japaneseData.title.includes(search.value) I don't get a match...
How do I do this correctly?
Okay, after further inspection, the comments were correct and includes was finding the substring. This is all happening inside of a filter() and I'm trying to return the objects that match...
After changing my code to:
let filteredArrayofObjects = Lists.houseLists.filter(house => house.building_name.includes(query.search));
I was getting back some but not all. Problem cases:
"アーバイルスパシエ芝浦BAY-SIDE".includes("エ芝浦"); // this evaluates to true, but does not get included in my filtered array...
Okay, further digging, it seems the issue is I need to wait for the filter process before returning the results... haven't yet found a solution to that just yet.
async filter(arr, callback) {
return (await Promise.all(
arr.map(async item => {
return (await callback(item)) ? item : undefined;
})
)).filter(i => i !== undefined);
}
handleFilterLists = async (query = {}) => {
const { Lists } = this.props;
let searchResults = await this.filter(Lists.houseLists, async house => {
return house.building_name.includes(query.search);
// the final evaluation to look similar to this:
// var newArray = homes.filter(function (el) {
// return el.price <= 1000 &&
// el.sqft >= 500 &&
// el.num_of_beds >=2 &&
// el.num_of_baths >= 2.5;
// });
});
this.setState({ searchResults });
}
Okay, so, I'm trying to set state.searchResults after the filter method has checked for matching objects in the array Lists.houseLists...
includes returns true or false if the substring is detected or not. If you want the index of where the first detected substring begins, use indexOf.
I used your sample source and search text with includes and it returns true.
Edit:
I used your updated data and this still works. https://codepen.io/anon/pen/RMWpwe
const sourceText = 'アーバイルスパシエ芝浦BAY-SIDE';
const searchText = 'エ芝浦';
const lists = [
'スパシエ',
'芝浦BAY-SIDE',
'エ芝浦',
'パシエ芝浦BAY'
];
console.log(lists.filter(item => item.includes(searchText)));
// ["エ芝浦", "パシエ芝浦BAY"]

Categories