How to extract longest word from an array? JavaScript/JSON - javascript

I want to create a function that takes a string as its parameter and extracts the longest word. If there are multiple words of the same length (max), It extracts the first one. (By the way, the function ignores numbers and punctuation). Anyways, here's the code:
function extractLongest(testString){
var lenArr = [];
var finalResult = "";
window.onload = function(){
testString = testString.replace(/[^a-z " "]/gi, '');
testString = testString.split(" ");
for (var counter = 0; counter < testString.length; counter++){
lenArr[counter] = parseInt(testString[counter].length);
}
lenArr = lenArr.sort();
for (var counterTwo = 0; counterTwo < testString.length; counterTwo++){
if(parseInt(testString[counterTwo].length) == Math.max(...lenArr)){
finalResult = testString[counterTwo];
break;
}
}
}
return finalResult;
}
The problem is that it always returns "string" (the type of the variable, not its value.)

The problem is your use of window.onload inside a function. This is only setting the handler on the window, which will only run when an onload event fires. Your function does this and then immediately returns finalReuslts which will still be an empty string. Presumably, you want all this code to run when you call the function. It's not clear why you are doing that; removing it makes the function work:
function extractLongest(testString){
var lenArr = [];
var finalResult = "";
testString = testString.replace(/[^a-z " "]/gi, '');
testString = testString.split(" ");
for (var counter = 0; counter < testString.length; counter++){
lenArr[counter] = parseInt(testString[counter].length);
}
lenArr = lenArr.sort();
for (var counterTwo = 0; counterTwo < testString.length; counterTwo++){
if(parseInt(testString[counterTwo].length) == Math.max(...lenArr)){
finalResult = testString[counterTwo];
break;
}
}
return finalResult;
}
console.log(extractLongest("hello my name is stephen"))
In case it's useful, there is a simpler way to do this with reduce():
function extractLongest(testString){
testString = testString.replace(/[^a-z " "]/gi, '');
testString = testString.split(" ");
return testString.reduce(function(a, b) {
return a.length > b.length ? a : b
});
}
console.log(extractLongest("hello my designation is stephen"))

Related

How can I extract all contained characters in a String? [duplicate]

I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)

Any alternative way of using this .length & .split()?

I want to split lower, upper & also the value of textBox without using .split() and also I want
to find the length of the string without using .length. Can anybody solve my problem I am tried but
I cannot find the exact logic for this problem.
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function Print() {
var input = document.getElementById('demo').value;
document.write(document.getElementById('demo1').innerHTML = toUpper(input));
}
function toUpper(input) {
var upperCase = uppercase.split(""); //other way to split uppercase
var lowerCase = lowercase.split(""); //other way to split lowercase
var inputText = input.split(""); //other way to split input
var newText = "";
var found;
for (var i = 0; i < inputText.length; i++) { //not using .length to other way to find the size of inputText
found = false;
for (var ctr = 0; ctr < lowerCase.length; ctr++) { //not using .length other way to find the size of lowerCase
if (inputText[i] == lowerCase[ctr]) {
found = true;
break;
}
}
if (found) { //true
newText = newText + upperCase[ctr];
} else {
newText = newText + inputText[i];
}
}
return newText;
}
You can count the length of a string using the array function reduce.
Reduce loops over all elements in an array and executes a function you give it to reduce it to one value, you can read more here.
To get reduce working on strings, you need to use Array.from, like this:
Array.from(lowerCase).reduce((sum, carry) => sum + 1, 0) // 26
Reduce accepts a starting argument, which we set to zero here.
This way you do not need to use the split or length functions.
You don't need to check if the input is in a string either, you can use charCodeAt() and fromCharCode().
If you take your input and loop through it using Array.from() then forEach, you can get something which looks like this:
function print() {
const input = document.querySelector('#input').value;
document.querySelector('#target').value = stringToUpper(input);
}
function stringToUpper(input) {
let output = "";
Array.from(input).forEach(char => output += charToUpper(char));
return output;
}
function charToUpper(char) {
let code = char.charCodeAt(0);
code >= 97 && code <= 122 ? code -= 32 : code;
return String.fromCharCode(code);
}
<div>
<input id="input" placeholder="enter text here">
</div>
<button onclick="print()">To Upper</button>
<div>
<input id="target">
</div>
The key line is where we take the output and add the char (as upper) to it:
output += charToUpper(char)
If you don't know about arrow functions, you can read more here
This line:
code >= 97 && code <= 122 ? code -= 32 : code;
is just checking if the char is lower case (number between 97 and 122) and if so, subtracting 32 to get it to upper case.
The reason it is subtract not add is in utf-16, the chars are laid out like this:
ABCDEFGHIJKLMNOPQRTUWXYZabcdefghijklmnopqrtuwxyz
See here for more
I don't know what you mean by "split the value of textBox", but one way to determine the length of a string without using .length would be to use a for...of loop and have a counter increment each time it runs to keep track of the number of characters in the string.
let string = 'boo'
let lengthCounter = 0
for (let char of string) {
lengthCounter++
}
//lengthCounter = 3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
You can define your own split and length functions:
function mySplit(a){
var counter = 0;
rslt = [];
var val = a[counter];
while(typeof val != "undefined"){
rslt.push(a[counter]);
counter ++;
val = a[counter];
}
return rslt;
}
function myLength(a){
var counter = 0;
var val = a[counter];
while(typeof val != "undefined"){
counter ++;
val = a[counter];
}
return counter;
}
Your function now should be like:
function toUpper(input) {
var upperCase = mySplit(uppercase);
var lowerCase = mySplit(lowercase);
var inputText = mySplit(input);
var newText = "";
var found;
for (var i = 0; i < myLength(inputText); i++) {
found = false;
for (var ctr = 0; ctr < myLength(lowerCase); ctr++) {
if (inputText[i] == lowerCase[ctr]) {
found = true;
break;
}
}
if (found) { //true
newText = newText + upperCase[ctr];
} else {
newText = newText + inputText[i];
}
}
return newText;
}
The simplest way would be to just use the build in function of javascript .toUpperCase() (see example 1). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
Else if you insist on using a for.loop you may do so aswell (see example two). You do not need the split() function since a string already is an arrayof characters. Also be aware that not all characters in the web have lowercase counterparts, so the logic itself is flawed.
//REM: This lines are not required.
/*
var lowercase = "abcdefghijklmnopqrstuvwxyz";
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function Print() {
var input = document.getElementById('demo').value;
document.write(document.getElementById('demo1').innerHTML = toUpper(input));
}
*/
//REM: Version 1 (using string.toUpperCase())
(function toUpper1(input){
var tReturn = (input || '').toUpperCase();
console.log('toUpper1', tReturn);
return tReturn
}('abcDEFghiJKL'));
//REM: Version 2 (using your way)
(function toUpper2(input){
var tReturn = '';
if(input && input.length){
for(let i=0, j=input.length; i<j; i++){
tReturn += (input[i] === input[i].toLowerCase()) ? input[i].toUpperCase() : input[i]
}
};
console.log('toUpper2', tReturn);
return tReturn
}('abcDEFghiJKL'));

Check if string contains substring without using indexOf - Javascript

My function is trying to check if string contains substring without use of indexOf or regex match or any standard JS methods.
Please check this jsfiddle: https://jsfiddle.net/09x4Lpj2/
var string1 = 'applegate';
var string2 = 'gate';
function containsString(string1, string2){
var j = 0;
var k = 0;
var contains = 'false';
var charArray1 = string1.split('');
var charArray2 = string2.split('');
for(var i = 0; i < charArray2.length; i++){
j = i;
if(charArray1[j++] != charArray2[k++]){
contains = 'false';
}else{
contains = 'true';
}
}
console.log(contains);
}
containsString(string1, string2);
This solution works only when the indexes are the same between the two strings (ex. applegate and apple). But will not work if the indexes are not the same (ex. applegate and gate). How do I manipulate the iterative values correctly so that the function returns true for both situations?
you can try this modified script of yours.
var string1 = 'applegate';
var string2 = 'gate';
var string3 = 'apple';
var string4 = 'leg';
var string5 = 'banana';
function containsString(string1, string2){
var charArray1 = string1.split('');
var charArray2 = string2.split('');
var match = 0;
// iterate from start of 1st string until length of 1st string minus length of 2nd string
// you don't need to iterate the last part that is not longer than 2nd string since it will be false
for(var i = 0; i < charArray1.length - charArray2.length + 1; i++){
// reset match counter on every iteration
match = 0;
// iterate the 2nd string
for(var j = 0; j < charArray2.length; j++){
// compare corresponding char location
if(charArray1[i+j] == charArray2[j]){
match++;
// just to check in console
console.log(i, j, match, charArray1[i+j], charArray2[j]);
} else {
// just to check in console
console.log(i, j, match, charArray1[i+j], charArray2[j]);
// if not match, just skip current check
break;
}
// if match already found, stop the checks, and return true
if(match == charArray2.length){
return true;
}
}
}
// match not found until end of iteration
return false;
}
console.log(containsString(string1, string2));
console.log(containsString(string1, string3));
console.log(containsString(string1, string4));
console.log(containsString(string1, string5)); // haystack does not contain needle
console.log(containsString(string4, string1)); // haystack is shorter than needle
Welcome to SO.
Regex can be used.. Unless even that is also prohibited..
function containsString(string1, string2){
console.log(string1.match(string2) != null ? "Yes" : "No");
}
Regex
This code has a logical problem,Only to determine whether the last character of A is equal to the corresponding character of B,Maybe the following code is what you want,add a line of code.
var string1 = 'applegate';
var string2 = 'gate';
function containsString(string1, string2){
var j = 0;
var k = 0;
var contains = 'false';
var charArray1 = string1.split('');
var charArray2 = string2.split('');
for(var i = 0; i < charArray2.length; i++){
j = i;
if(charArray1[j++] != charArray2[k++]){
contains = 'false';
break;
}else{
contains = 'true';
}
}
console.log(contains);
}
Check this without using any inbuilt functions
function subSearch(long,short){
var count = 0
for(i = 0;i < long.length; i++){
for(j = 0;j < short.length; j++){
if(short[j] != long[i + j]){
break;
}
if((j+1) == short.length){
count++;
}
}
}
return count;
}

JavaScript code for counting the words input into an input box

I am supposed to write a function which can count the words in the text area but my code count only the first word, you can see the code here:
link to my code
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor){
var myTextareaElement =document.getElementById("myWordsToCount").value;
var haveByNow = 0;
for (var i = 0; i < wordcount.length; i++)
if (wor[i] === " ") {
haveByNow = +1;
}
haveByNow += 1;
document.getElementById("wordcount").innerHTML = haveByNow;
}
Why not splitting on empty character that textarea value and get arraylength: Check the snippet below
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor) {
var myText = this.value.trim();
var wordsArray = myText.split(/\s+/g);
var words = wordsArray.length;
document.getElementById("wordcount").innerHTML = words;
};
<textarea id="myWordsToCount"></textarea>
<span id="wordcount"></span>
You have some typos and errors, see working code:
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor){
var words = myTextareaElement.value;
var haveByNow = 1;
for (var i = 0; i < words.length; i++) {
if (words[i] == " ") {
haveByNow += 1;
}
}
document.getElementById("wordcount").innerHTML = haveByNow;
}
<textarea id="myWordsToCount" rows="5" cols="60"></textarea><br>
The wordcount is: <span id="wordcount"></span><br>
This line:
haveByNow = +1;
...is not the same as:
haveByNow += 1;
The former sets haveByNow to 1, the other increments. This is why you'd be seeing a result of 1 every time.
Another problem is this expression in your for loop:
wordcount.length
wordcount is the name of your function, and wordcount.length is the number of parameters of that function, which is not going to be what you want. myTextareaElement, which is the value of the input is what you want to get the length of:
for (var i = 0; i < myTextareaElement.length; i++) ...
Though as #itsgoingdown points out, there are better ways to get a word count.

Javascript Function to split and return a value from a string

I am trying to grab a certain value. I am new to javascript and I can't figure out why this is not working.
If I parse "kid_2" I should get "kostas". Instead of "Kostas" I always get "02-23-2000". So I must have a logic problem in the loop but I am really stuck.
function getold_val(fieldname,str){
var chunks=str.split("||");
var allchunks = chunks.length-1;
for(k=0;k<allchunks;k++){
var n=str.indexOf(fieldname);
alert(chunks[k]);
if(n>0){
var chunkd=chunks[k].split("::");
alert(chunkd);
return chunkd[1];
}
}
}
var test = getold_val('kid_2','date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||');
alert(test);
A regex may be a little more appealing. Here's a fiddle:
function getValue(source, key){
return (new RegExp("(^|\\|)" + key + "::([^$\\|]+)", "i").exec(source) || {})[2];
}
getValue("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","kid_2");
But if you want something a little more involved, you can parse that string into a dictionary like so (fiddle):
function splitToDictionary(val, fieldDelimiter, valueDelimiter){
var dict = {},
fields = val.split(fieldDelimiter),
kvp;
for (var i = 0; i < fields.length; i++) {
if (fields[i] !== "") {
kvp = fields[i].split(valueDelimiter);
dict[kvp[0]] = kvp[1];
}
}
return dict;
}
var dict = splitToDictionary("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","||","::");
console.log(dict["date_1"]);
console.log(dict["date_2"]);
console.log(dict["kid_1"]);
console.log(dict["kid_2"]);​
This works, here's my fiddle.
function getold_val(fieldname,str) {
var chunks = str.split('||');
for(var i = 0; i < chunks.length-1; i++) {
if(chunks[i].indexOf(fieldname) >= 0) {
return(chunks[i].substring(fieldname.length+2));
}
}
}
alert(getold_val('kid_2', 'date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||'));
The issue with your code was (as #slebetman noticed as well) the fact that a string index can be 0 because it starts exactly in the first letter.
The code is almost the same as yours, I just didn't use the second .split('::') because I felt a .substring(...) would be easier.
There are two bugs. The first error is in the indexOf call:
var n = str.indexOf(fieldname);
This will always return a value greater than or equal to 0 since the field exists in the string. What you should be doing is:
var n = chunks[k].indexOf(fieldname);
The second error is in your if statement. It should be:
if(n >= 0) {
...
}
or
if(n > -1) {
...
}
The substring you are looking for could very well be the at the beginning of the string, in which case its index is 0. indexOf returns -1 if it cannot find what you're looking for.
That being said, here's a better way to do what you're trying to do:
function getold_val(fieldName, str) {
var keyValuePairs = str.split("||");
var returnValue = null;
if(/||$/.match(str)) {
keyValuePairs = keyValuePairs.slice(0, keyValuePairs.length - 1);
}
var found = false;
var i = 0;
while(i < keyValuePairs.length && !found) {
var keyValuePair = keyValuePairs[i].split("::");
var key = keyValuePair[0];
var value = keyValuePair[1];
if(fieldName === key) {
returnValue = value;
found = true;
}
i++;
}
return returnValue;
}

Categories

Resources