I need to find the length of the longest string in the given array. It should return 0 if the array is empty.
So here's my try:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for(var i=0; i< arr.length; i++){
if(arr[i] > biggestNum){
biggestNum = arr[i];
}
}
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output); // --> MUST RETURN 5
But this one did not work. Any idea or is there any better option to do this?
To throw another alternative into the mix: Math.max can be fed the lengths as arguments (by mapping them on the input) to get the longest string:
function getLengthOfLongestElement(arr) {
return Math.max(0,...arr.map(s=>s.length));
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
This is apparently a reducing job and can simply be implemented as follows;
var ss = ['one', 'two', 'three'],
ln = ss.reduce((r,s) => r > s.length ? r : s.length, 0);
console.log(ln);
You should test with arr[i].length instead of arr[i] and you should return biggestNum at the end of your function:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
Demo:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
You should use the string length property. So instead of arr[i] it will be arr[i].length
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
My preferred solution is using reduce.
const arr = ['one', 'two', 'three'];
const maxLength = arr.reduce((acc, item) => Math.max(acc, item.length), 0);
console.log(maxLength)
For zero element just check if the array length is zero or not else arr[i].length will return the length of the string
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
if (arr.length > 0) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
} else if (arr.length == 0) {
biggestNum = 0
}
return biggestNum
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
Related
i need make function like this:
Function add(arr,...newVal){
}
array = [1,2,3];
add(array,0)
console.log(array); //i need here to print [0,1,2,3]
iam make function as push like that:
Function add(arr,...newVal){
for(var i=0; i<arr.length; i++){
arr[arr.length]=newVal[i];
}return arr.length;
}
array = [1,2,3];
add(array,4)
console.log(array); // here to print [1,2,3,4]
const unshift = (arr, ...newVal) => {
let i= arr.length + newVal.length -1;
for( i ; i >= newVal.length; i--) {
arr[i] = arr[i - newVal.length ];
}
for(i; i >= 0; i--) {
arr[i] = newVal[i];
}
return arr;
}
Try this:
const unshift = (arr, newVal) => {
for(let i = arr.length; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = newVal;
return arr;
}
function findShortestElement(arr) {
var shortestElement = [];
for (var i = 0; i<arr.length; i++) {
if(arr[i].length > shortestElement) {
}
}
return shortestElement;
}
var output = findShortestElement(['a', 'two', 'three']);
console.log(output); // --> 'a'
Got stuck here, i'm assuming I could do this without the filter method but i'm not sure how. I usually set the shortestElement to infinity then do if an if statement. Any help on how to accomplish this?
function findShortestElement(arr){
return arr.sort((a,b)=>a.length-b.length)[0]
}
Here is the solution with Javascript Reduce:
function findShortestElement(arr) {
return arr.reduce(function(a, b) {
return a.length <= b.length ? a : b;
})
}
var output = findShortestElement(['a', 'two', 'three']);
console.log(output); // --> 'a'
function findShortestElement(arr = []) {
let shortestElementIndex = -1, shortestElementLength = Infinity;
for (let i = 0; i < arr.length; i++) {
// if current element's length is less than shortestElementLength, update
if(arr[i].length < shortestElementLength) {
shortestElementIndex = i;
shortestElementLength = arr[i].length;
}
}
return arr[shortestElementIndex];
}
var output = findShortestElement(['a', 'two', 'three']);
console.log(output);
Just followed your way.
function findShortestElement(arr) {
var shortestElement = arr[0];
var shortestLength = arr[0].length
for (var i = 1; i<arr.length; i++) {
if(arr[i].length < shortestLength) {
shortestElement = arr[i];
shortestLength = arr[i].length
}
}
return shortestElement;
}
var output = findShortestElement(['a', 'two', 'three']);
console.log(output); // --> 'a'
function findShortestElement(arr) {
if (arr.length <= 0) {
return '';
}
let shortest = arr[0];
for (let i = 0; i < arr.length; i++) {
if (arr[i].length < shortest.length) {
shortest = arr[i];
}
}
return shortest;
}
I have function that defines most frequent item in array and returns it. It waorks as expected except I want to show last item if there are two or more items with the same frequency score. For expample, I have an array ['grape', 'lemon', 'apple', 'grape', 'lemon'], function will return 'grape' and my goal is to return 'lemon' in this case. I tried to use if statement but didn't figured the right way. Here is js code:
let fruits = ['grape', 'lemon', 'apple', 'grape', 'lemon'];
(function(array) {
let mf = 1;
let m = 0;
let item;
for (let i = 0; i < array.length; i++) {
for (let j = i; j < array.length; j++) {
if (array[i] == array[j])
m++;
if (mf < m) {
mf = m;
item = array[i];
}
}
m = 0;
}
console.log(item);
return item;
})(fruits);
Any help would be appreciated.
Just use <= instead of <
let fruits = ['grape', 'lemon', 'apple', 'grape', 'lemon'];
(function(array) {
let mf = 1;
let m = 0;
let item;
for (let i = 0; i < array.length; i++) {
for (let j = i; j < array.length; j++) {
if (array[i] == array[j])
m++;
if (mf <= m) {
mf = m;
item = array[i];
}
}
m = 0;
}
console.log(item);
return item;
})(fruits);
You could take a single loop with an object for counting the items and an array for the last item of the greatest count.
function lastTop(array) {
var count = {},
last = [],
value;
for (value of array) last[count[value] = (count[value] || 0) + 1] = value;
return last.pop();
}
var array = ['grape', 'lemon', 'apple', 'grape', 'lemon'],
last = lastTop(array);
console.log(last);
Just reverse your loops, start at the end of the array, and you can set m = 1 and j = i - 1 so that i will never equal j to avoid unnecessary comparison and addition:
let fruits = ['grape', 'lemon', 'apple', 'grape', 'lemon'];
(function(array) {
let mf = 1;
let m = 1;
let item;
for (let i = array.length - 1; i > 0; i--) {
for (let j = i - 1; j >= 0; j--) {
if (array[i] == array[j])
m++;
if (mf < m) {
mf = m;
item = array[i];
}
}
m = 0;
}
console.log(item);
return item;
})(fruits);
One possible solution is loop the array from higher index to lower index
let fruits = ['grape', 'lemon', 'apple', 'grape', 'lemon'];
(function(array) {
let mf = 1;
let m = 0;
let item;
for (let i = array.length -1; i >=0 ; i--) {
for (let j = i; j >= 0; j--) {
if (array[i] == array[j])
m++;
if (mf < m) {
mf = m;
item = array[i];
}
}
m = 0;
}
console.log(item);
return item;
})(fruits);
I'm doing an assignment that asks for the length of the shortest string in an array. It should return 0 if the array is empty. I keep getting an error message that it doesn't handle ties.
Also, a test array arr = ['one', 'two', 'three', 'aa'] returns a value of 3 instead of 2 as it should...
function getLengthOfShortestElement(arr) {
var array;
if (arr.length > 0) {
for (i = 0; i < arr.length; i++) {
if (typeof array === "undefined") {
array = arr[i].length;
} else if (arr[i].length < array) {
array = arr[i].length;
}
return array;
}
} else {
return 0;
}
}
Someone pointed it out in the comments, just move your return out of the body of the for loop.
function getLengthOfShortestElement(arr) {
var array;
if (arr.length > 0) {
for (i = 0; i < arr.length; i++) {
if (typeof array === "undefined") {
array = arr[i].length;
} else if (arr[i].length < array) {
array = arr[i].length;
}
}
return array;
} else {
return 0;
}
}
var arr = ['one', 'two', 'three', 'aa'];
document.write(getLengthOfShortestElement(arr));
I want to sort a string in javascript without using a built in method, just by using for's and comparisons like 'a' > 'b';
Something that doesn't work:
function replaceAt(str, i, char) {
return str.substr(0,i) + char + str.substr(i + 1)
}
function swap(str, i1, i2) {
return replaceAt(replaceAt(str, i1, str[i2]),i2,str[i1]);
}
function sort(str) {
var sorted = str;
for (var i = 0; i < str.length; i++) {
if (str[i] > str[i + 1]) {
str = swap(str, i, i+1)
}
}
return str;
}
Pseudo-code or books, courses recommendations on programming are welcome!
Your code is not applying any sort algorithm logic, I recommend you to read atleast 1 to solve your problem.
Below is the program, which produces the expected output from your program using selection sort.
swap and replace functions works fine.
function sort(str) {
var sorted = str;
//Selection sort
for (var i = 0; i < str.length; i++) {
for(var j = i + 1; j < str.length - 1; j++) {
if (str[i] < str[j]) {
str = swap(str, i, j)
}
}
}
return str;
}
console.log(sort("zaasfweqrouoicxzvjlmmknkniqwerpopzxcvdfaa"));
//output: aaaaccdeeffiijkklmmnnoooppqqrrsuvvwwxxzzz
function sort(arr) {
arr = arr.split("");
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[j] > arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr.join("");
}
console.log(sort("dcna"));
function sort(arr) {
arr = arr.split("");
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[j] > arr[i]) {
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]
}
}
}
return arr.join("");
}
console.log(sort("dcna"));
Note: no need of using temp variable
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
array=[4, 10, 2, 9, 6, 3, 13, 5];
function arrayOperations()
{
var count = array.length - 1,
temp,
j,
i;
for (j = 0; j < count; j++)
{
for (i = 0; i < count; i++)
{
if (array[i] > array[i + 1])
{
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
}
document.write("ascending order is <br>")
for(k=0;k<=array.length-1;k++){
document.write(array[k]+ "<br>");
}
document.write("descending order is <br>")
for(k=array.length-1;k>=0;k--){
document.write(array[k]+ "<br>");
}
document.write("biggest number is <br>")
for(k=array.length-1;k>=0;k--){
if((array[k])>array[k-1]){
document.write(array[k]+"<br>")
break;
}
}
document.write("smallest number is <br>")
for(k=0;k<=array.length;k++){
if((array[k])<array[k+1]){
document.write(array[k]+"<br>")
break;
}
}
}
</script>
<title></title>
</head>
<body>
array=[4, 10, 2, 9, 6, 3, 13, 5]
<br>
<input type="button" onclick="arrayOperations()" value="find">
</body>
</html>
//generic sort function to sort a word
function sortArray(str){
let strr = str.split('');
for(var index = 0 ;index <strr.length ;index ++ ){
for(var index1 = 0;index1<(strr.length-index) ;index1++){
let temp;
if( strr[index1] > strr[index1+1] ){
temp = strr[index1] ;
strr[index1] = strr[index1 +1];
strr[index1+1] =temp;
}
}
}
return(strr.join(''));
}
//data set to sort
let data = "Hey Goodmorning How are you";
let result;
let data1 =data.split(' ');
data1.forEach(value => {
value = sortArray(value.toLowerCase());
if(result){
result += " ";
result += value;
}
else {result = value;}
});
console.log(result);