How to print the 2 most repeated strings in an array [duplicate] - javascript

This question already has answers here:
Counting the occurrences / frequency of array elements
(39 answers)
Closed last year.
First of all I apologize this may be trivial but I'm stuck, I search in an array the string that repeats the most and print the 2 that repeat the most.
I have wanted to do Case or multiple if, but I also get the idea of a map(), in short I do not find an efficient way to implement it.
thank you very much in advance
const clientes=['cliente1','cliente2', 'cliente3', 'cliente2', 'cliente3', 'cliente4'];
for(let x = 0; x < clientes.length; x++)
{
}
console.log('CLIENTES', clientes)

Loop and count. your approach goes to right direction.
let counts = {};
const clientes = ['cliente1','cliente2', 'cliente3', 'cliente2', 'cliente3', 'cliente4'];
clientes.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)

Related

Returning the full contents of an array [duplicate]

This question already has answers here:
Does return stop a loop?
(7 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
function monkeyCount(n) {
for (i=1; i<=n; ++i){
let monkeyArray=[i];
return monkeyArray[i];
}
}
Another rookie question lol. I need to return the values of an entire array using the return statement and not the console.log. If I pass a number such as 5 to the function I need to return 1,2,3,4,5 your help much appreciated:0)
It looks like you want to append values to the array not reassign the array at every iteration of the loop. Try this:
const monkeyArray = [];
for(let i = 1; i<= n; i++){
monkeyArray.push(i);
}
return monkeyArray;
There are also many ways to do this such as with the lodash library where you can just call _.range(1, 6) to get an array from [1,6)
This is pretty simple, you just have try this on browser console.
function monkeyCount(n) {
let monkeyArray = [];
for (i=1; i<=n; ++i) {
monkeyArray[i-1] = i;
}
return monkeyArray.join(',');
}

How do I fill an array using a for loop without having identical numbers? [duplicate]

This question already has answers here:
Generating non-repeating random numbers in JS
(20 answers)
Unique random values from array of unique values javascript
(2 answers)
Closed 2 years ago.
I have been reworking this a few times and thought this would resolve the issue. I am still getting two of the same numbers though. Also, the array amount will fluctuate from 8 values which I have set the array for, but then go to 9 values which I don't quite understand. Any help would be much appreciated.
function totalQuestion(){
let amountOfQuestionTotal = myObj.length // amount of question
var amountOfQuestionsNeeded = [8];// am
let numberNeeded = 8;
for(var i = 0; i < numberNeeded; i++) {
var countNumber = Math.floor(Math.random() * amountOfQuestionTotal)
var n = amountOfQuestionsNeeded.includes(countNumber)
if (countNumber != n) {
amountOfQuestionsNeeded.push(countNumber);
}
}
return amountOfQuestionsNeeded;
}
totalQuestion();
console.log(totalQuestion());

String to array js [duplicate]

This question already has an answer here:
Split string into array of equal length strings
(1 answer)
Closed 2 years ago.
I want to convert a String '1234567' to Array
like this['123','456','7']
i have try this:
let str='1234'
let num=3;
let temp='';
let array=str.split('')
let newArr=[];
for(let i = 0;i<array.length;i++){
if((i+1)%num!==0){
temp+=array[i]
}else{
temp+=array[i]
newArr.push(temp)
temp='';
}
}
console.log(newArr)
but it miss the 4
When the loop finishes, temp may be non-empty without having been added to newArr. One way to handle this would be to check for this scenario after the loop and handle accordingly.
// after the for-loop
if (temp) {
newArr.push(temp)
}

How to immutably insert into a sorted array? [duplicate]

This question already has answers here:
Efficient way to insert a number into a sorted array of numbers?
(18 answers)
Closed 3 years ago.
How do I immutably insert an element into a sorted array? (Let's assume an array of integers for simplicity)
The reason for this question: I'm writing a reducer for a React app, where the order of elements in my particular array is important.
The closest solution I've found is this one here, but it doesn't cover insertions into a sorted array.
Try this one.
let sortedArr = [1,2,5,9,12];
const newItem = 7;
for (let i = 0; i < sortedArr.length; i++) {
if (newItem <= sortedArr[i]) {
sortedArr = [...sortedArr.slice(0, i), newItem, ...sortedArr.slice(i)];
break;
}
}
console.log(sortedArr);

Compare two arrays of "strings" to check if they are equal [duplicate]

This question already has answers here:
Remove items from one array if not in the second array
(5 answers)
Closed 7 years ago.
Good day,
I have two arrays of strings. Strings are just numeric dates (eg: "01/01/2016"...).
I would like to know if there is a good/fast way to compare the two arrays and remove the strings from one array, which are not present in second one.
Example:
First array: ["01/01/2016","02/02/2015", "03/03/2014"]
Second array: ["01/01/2016", "02/02/2015"]
The string "03/03/2014" should be removed from the first array.
I have tried doing it though for() loops of both array lengths, but it seems to be very slow, because the arrays are big (abt. 1000+) indexes in each, like this:
for (var a = 0; a < oilDateArray.length; a++) {
for (var b = 0; b < fuelDateArray.length; b++) {
if (fuelDateArray[b] !== oilDateArray[a]) {
console.log("fuelDateArray not present: " + fuelDateArray[b]);
}
}
}
Is there a specific function/method, which I could use in order to perform the above operation faster?
Thanks in advance and have a nice day!
Try this :
for (var i = 0; i < firstArray.length; i++){
if (secondArray.indexOf(firstArray[i]) == -1){ // indexOf is -1 if not found
firstArray.splice(i, 1); // Remove 1 value at index i
i--; // To re-adjust the index value which is 1 less because of the splice
}
}
It may also be a bit slow, you can try with your array : https://jsfiddle.net/tyrsszaw/4
with jquery
$(array1).filter(array2);
If you have access to Set:
function intersect(arr1, arr2){
var s = new Set(arr1);
return arr2.filter(function(el){
return s.has(el);
});
}
i use jquery for array operations and i'll edit one for your need and paste here, i hope this can help you:
var arr1 = ["01/01/2016","02/02/2015", "03/03/2014"];
var arr2 = ["01/01/2016", "02/02/2015"];
var diff = [];
jQuery.grep(arr2, function(t) {
if (jQuery.inArray(t, arr1) == -1) diff.push(t);
});
alert(diff);​ // what was different will be alerted
i also found this code on stackoverflow sometime ago.
Update: Here is performance related topic you might be interested
Performance of jQuery.grep vs. Array.filter
tldr;
it says grep is about 3 times faster. So stick with my solution. :)

Categories

Resources