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);
Related
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;
}
This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
for (var i = spaces.length - 1; i >=0; i = i - 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."
Then "array2" is an array of "array1" reversed.
Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.
Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".
I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.
You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
Here is my best crack at it.
const reverseStr = (input) => {
const revArr = input.replaceAll(' ', '').split('').reverse();
for (let i = 0; i < revArr.length; i++) {
if (input[i] === ' ') revArr.splice(i, 0, ' ');
}
return revArr.join('');
}
let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
// console.log(val.split('').reverse().join(''))
return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))
how can i get elements uniquely from an array if aa is twice time it should not count in a result if it is if a is three times it should count 1
var string = "aaabbccddde" // Expected result ade
var toArray = string.split("")
console.log(toArray)
var newArr = []
for(let i =0; i<toArray.length; i++) {
if(newArr.indexOf(toArray[i]) === -1) {
newArr.push(toArray[i])
}
}
console.log(newArr)
can't find the solution yet please guide thank
Maybe this function can help you:
function getUniques(str) {
const uniques = [];
const strs = str.split("");
for (let i = 0; i < strs.length; i++) {
const elm = strs[i];
for (let j = i; j < strs.length; j++) {
if(elm === uniques[uniques.length - 1]) break;
if (elm !== strs[j + 1]) {
uniques.push(elm);
break;
}
}
}
return uniques.join("");
}
Sample:
getUniques("aaaadaaabbbcccdeeeee22222222222232") // adabcde232
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);
Given arr = ['mat','cat','fat']
A function getComb(arr, n = 2) where n is the number of words each combination must have.
Expected results:
mat cat
mat fat
cat fat
I could not modify the code below any further to get the desired results. Any idea? thx
Thanks to Knskan3:
'getCombinations': (arr, n) => {
let i, j, k, elem, l = arr.length, childperm, ret = [];
if (n === 1) {
for (let i = 0; i < arr.length; i++) {
ret.push([arr[i]]);
}
return ret;
}
else {
for (i = 0; i < l; i++) {
elem = arr.shift();
for (j = 0; j < elem.length; j++) {
childperm = lib.getCombinations(arr.slice(), n - 1);
for (k = 0; k < childperm.length; k++) {
ret.push([elem[j]].concat(childperm[k]));
}
}
}
return ret;
}
},
I suggest a space-efficient generator function:
// Generate all k-combinations of first n array elements:
function* combinations(array, k, n = array.length) {
if (k < 1) {
yield [];
} else {
for (let i = --k; i < n; i++) {
for (let combination of combinations(array, k, i)) {
combination.push(array[i]);
yield combination;
}
}
}
}
// Example:
console.log(...combinations(['mat', 'cat', 'fat'], 2));