This question already has answers here:
Get the element with the highest occurrence in an array
(42 answers)
get most occurring elements in array JavaScript
(3 answers)
Frequent number in Javascript
(7 answers)
Closed 3 years ago.
I am currently being faced with this problem where I am trying to find the most occurring or frequent element in an array.
For example:
const arr = [1,2,1,1,1,2,2,2,1] (Most occuring is: 1)
Follow up: What if I want to get the second-most occurring element?
Here's my solution:
function returnMostOccurring(arr) {
const obj = {};
arr.forEach(item => {
if(!obj[item]) obj[item] = 1;
else obj[item]++;
})
const res = Object.entries(obj).sort((a,b) => b[1]-a[1]);
return res.shift();
}
I figured this is not the most optimal way to solve this problem (O(nLogN) time complexity)
What is the best way to handle this kind of use case?
You could take a single loop with a variable for the element with the actual max count and an object for keeping the counts of the elements.
function mostOccurringElement(array) {
var max = array[0],
counter = {},
i = array.length,
element;
while (i--) {
element = array[i];
if (!counter[element]) counter[element] = 0;
counter[element]++;
if (counter[max] < counter[element]) max = element;
}
return max;
}
const array = [1, 2, 1, 1, 1, 2, 2, 2, 1];
console.log(mostOccurringElement(array));
Related
This question already has answers here:
Fastest way to move first element to the end of an Array
(9 answers)
How to get the first element of an array?
(35 answers)
Closed 5 months ago.
I have an array which I have sorted from smallest integer to largest. The array data comes from backend and will be random numbers
// example array from backend
const arr = [400,30,10,-1]
const sortedArray = arr.sort((a, b) => a - b)
// [-1,10,30,400]
If the first index of the array is equal to -1 I want to remove it from the first position in the array and append it to the last position of the array.
For example if array is [-1, 10, 30, 400] I want to return [10,30,400,-1].
Edit: I am looking for the safest possible way and unsure to use splice(), filter() etc
shift the first element off the array and push it on the end.
const arr = [400,30,10,-1].sort();
if (arr[0] === -1) arr.push(arr.shift());
console.log(arr);
After your code you can check first element is -1 and then slice and push -1 to it
if(arr[0] == -1){
arr = arr.slice(1)
arr.push(-1)
}
I might have exaggerated the solution, but I am guessing it might help someone.
const beData = [400, 30, 10, -1];
const sortedData = beData.sort((a, b) => a - b);
const newArr = sortedData.reduce((prevValue, currValue) => {
if(currValue < 0) {
prevValue[1].push(currValue);
} else {
prevValue[0].push(currValue);
}
return prevValue;
}, [[], []]);
const result = [...newArr[0], ...newArr[1]];
console.log(result);
This question already has answers here:
Array map function doesn't change elements
(4 answers)
Why does this map function not mutate the values in the original array?
(3 answers)
Closed 2 years ago.
The problem is that I cannot subtract each index of an array from its element(number), using the array.prototype.map() method. I expected the subtraction to be valid, but it is not.
Here is the code:
const whiteSp = [ 5, 11 ];
whiteSp.map(function (ele, i) {
console.log(ele, i) // 5 0, 11 1
console.log(ele - i) // 5, 10
ele = ele - i;
return ele;
});
console.log(whiteSp) // expected [ 5, 10 ], but got [ 5, 11 ]
The second console.log indicates the computation has been made as seen by the value 10, but returns 11 for some reason.
I have also tried 'return ele - i' without its above line, but still does not work.
Ciao, you could try something like this:
let whiteSp = [ 5, 11 ];
whiteSp = whiteSp.map((ele, i) => { return ele - i; });
console.log(whiteSp)
and remember that map function returns a new array so you have to do whiteSp = whiteSp.map....
You need an assignment of the mapped values.
const
whiteSp = [5, 11],
result = whiteSp.map((ele, i) => ele - i);
console.log(result);
This question already has answers here:
How to find the array index with a value?
(12 answers)
Get the index of the object inside an array, matching a condition
(16 answers)
Closed 3 years ago.
Im trying to determine the location of a in a array. Im not really sure how to handle this case
const expect = require('chai').expect;
const answers = require('../src/arrays');
describe('arrays', function() {
let a;
beforeEach(function() {
a = [ 1, 2, 3, 4 ];
});
it('expect determine location of a in array', function(expect) {
expect(answers.indexOf(a, 3)).to.eql(2);
expect(answers.indexOf(a, 5)).to.eql(-1);
});
Try this!
var array = [ 1, 2, 3, 4 ];
function finding_index(element) {
return element === 2;
}
console.log(array.findIndex(finding_index));
This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
JavaScript is in array [duplicate]
(16 answers)
Closed 3 years ago.
I wanted to achieve a value in the array is present in the array variable or not.
var a = [1, 2, 3];
if (a === 1) {
alert("green");
}
So my goal is to check in the variable a holds the value 1 or not.
Use includes:
let a = [1, 2, 3]
if (a.includes(1))
console.log('exist');
else
console.log('not exist');
You need to loop through array members and check if any of the members has that value. Here's an example:
var a = [1,2,3];
for(let i = 0; i < a.length; i++){
if(a[i] == 1){
alert("green");
}
}
This question already has answers here:
Copy array by value
(39 answers)
Closed 6 years ago.
When I ran the code in browser console or in js fiddle, this code snaps off the browser. I don't understand why it does. Can some one show some light ?
var sample = [1, 2, 3, 4];
function arrDupli(sample) {
var mysample = sample;
for (var i = 0; i < sample.length; i++) {
mysample.push(sample[i]);
}
console.log(mysample);
}
arrDupli(sample);
you are creating an infinite loop, mysample and sample have both the same value, so you are basically just pushing the same value over and over.
Try creating and empty array instead var mysample = [];