Hello I want to ask how to find same number or string on array The output must be a number or string
Example
var arr = [1,2,4,4,5,1,1,1,8,9]
Do we need to use loop , function?
Hello I want to ask how to find same number or string on array The output must be a number or string
Example
var arr = [1,2,4,4,5,1,1,1,8,9]
Do we need to use loop , function?
You can create a frequency array. Admittedly this might not be the most efficient way. You can use dictionaries for this. I hope you know what dictionaries are.
function fun(arr) {
var sval;
var dict = new Object();
for (var val in arr) {
sval = string(val)
if(dict[sval] === undefined) {
dict[sval] = 1;
}
else {
dict[sval]++;
}
}
var max_count = -5;
var max_count_num;
for (var key in dict) {
if (max_count < dict[key]) {
max_count = dict[key];
max_count_num = Number(key);
}
}
}
First you create an Object, which is for our purposes serves as a dictionary, then you iterate through the array. If the key is not found, hence undefined, then we create such entry, else we increment the value which is the count by 1.
We then loop through the dictionary trying to find the number with the maximum value, hence the maximum count.
I hope this is what you are looking for. Please fix any errors in my code, I'm a bit rusty on JavaScript.
Iterate for each item on the array (i index), and iterate for each item for the rest of the array (j index, j = i+1), and create a count to any repetition of current item.
function maxRepeated(arr) {
// count global to keep the max value count
const maxRepeat = {
value: 0,
times: 0
};
for (var i = 0; i < arr.length - 1; i++) {
var maxLocal = 1; // to count ar[i] item repetitions
for (var j = i + 1; j < arr.length; j++) {
if (arr[j] == arr[i]) maxLocal++;
console.log( maxLocal )
console.log( "I " + i + " arr[i] " + arr[i] )
}
// check if maxLocal is great than max global
if (maxLocal > maxRepeat.times) {
maxRepeat.value = arr[i];
maxRepeat.times = maxLocal;
}
}
return maxRepeat;
}
const ar = [1, 2, 3, 1, 3, 5, 1, 1, 1, 5, 4, 3, 3, 2, 2, 3];
const b = ["LUNA", "LUNA", "JS", "JS", "JS"];
//console.log(maxRepeated(ar))
console.log(maxRepeated(b))