So I need to get the highest 3 values from an array, though I don't know how many values I need to check since that number will change periodically, I tried running this loop but it doesn't work.
numbers = new array();
numbers = (6,34,6623,22,754,2677,12)
var num1 = 0
var num2 = 0
var num3 = 0
for (var i=0; i<numbers.length;i++) {
if num1<numbers[i] {
num1 = numbers[i]
} else if num2<numbers[i] {
num2 = numbers[i]
} else if num3<numbers[i] {
num3 = numbers[i]
}
}
All of the other answers propose the correct and fast way to do this, i.e. to sort the array in descending order and take the first three elements.
If you're interested why your code did not work: The problem is that you need to keep track of each of the last found max values if a new one is found. You need to change your code to something like this:
const numbers = [6, 34, 6623, 22, 754, 2677, 12]
let max = 0;
let oneLowerToMax = 0;
let twoLowerToMax = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > max) {
twoLowerToMax = oneLowerToMax;
oneLowerToMax = max;
max = numbers[i];
}else if(numbers[i] > oneLowerToMax) {
twoLowerToMax = oneLowerToMax;
oneLowerToMax = numbers[i];
}else if(numbers[i] > twoLowerToMax) {
twoLowerToMax = numbers[i];
}
}
console.log(max, oneLowerToMax, twoLowerToMax) // prints 6623, 2677, 754
Sort the array in descending order and then get all 3 element by its index:
let numbers = new Array(6,34,6623,22,754,2677,12);
numbers.sort(function(a, b){return b-a});
console.log(numbers[0], numbers[1], numbers[2]);
you can sort array
var numbers = [1,65,8,98,689,12,33,2,3,789];
var topValues = [... numbers].sort((a,b) => b-a).slice(0,3);
there is a simpler way you can achieve this.
first, run a sort() on your array, then pick the highest ones.
const myArray = [7,4,99,10,55,1];
console.log(myArray.sort((a,b)=>b-a).slice(0, 3)) // [99, 55, 10]
Simply sort your array in descending order, then slice the first three values.
Note: .sort().reverse() is the speediest approach for sorting in descending order. See https://stackoverflow.com/a/52030227/129086
function getTopThree(arr) {
// spread avoids modifying the original array
return [...arr].sort().reverse().slice(0, 3);
}
getTopThree(numbers);
Whenever your numbers array is updated or changed, call getTopThree(numbers) again.
Related
The plan is:
sort 'arr' from less to greater.
push values in range of both number from arr, inclusively.
find smallest common number which dividible on each value from 'arrForAll' without reminder.
Assign to 'i' first value from 'arrForAll'.
Output 'while' condition isn't false. Condition is: 'i' don't divide on each value from 'arrForAll' without reminder.
I tried this:
function smallestCommons(arr) {
let sortedArray = arr.sort();
let arrForAll = []
for (let i = sortedArray[0]; i < sortedArray[1] + 1; i++) {
arrForAll.push(i)
}
for (let i = sortedArray[1]; arrForAll.every(x => i % x !== 0); i += i) {
console.log(i)
}
return arr;
}
console.log(smallestCommons([1, 5]));
But console output nothing.
What's wrong in code?
In conditioin of for loop it must use logic operators '<','>', etc.
So this situation while loop is more suitable solution
function smallestCommons(arr) {
var i=0;
let sortedArray = arr.sort();//here store sorted value
let arrForAll=[]
for(let i=sortedArray[0];i<sortedArray[1]+1;i++){
arrForAll.push(i)
}//store [x to y]
while(true){
i+=sortedArray[1];
if(arrForAll.every(x => i % x == 0)){
break;
}
}
return i;}
console.log(smallestCommons([23, 18]));//returns 6056820, [1,5] will return 60
I've got a assignment to make function that gives you a sorted array with 6 random numbers from 1 to 45. None of the array values should equal to one another.
I thought about a solution that would work in Java but the JavaScript console logs I get are pretty confusing. Could anyone help me out?
"use strict";
var numbers = [];
for(var x = 1; x <46;x++){
numbers.push(x);
}
function LottoTipp(){
var result = [];
for(var i = 0; i <6; i++){
var randomNum = Math.round(Math.random()* 45);
var pushed = numbers[randomNum];
result.push(pushed);
numbers.splice(randomNum)
}
return console.log(result) + console.log(numbers);
}
LottoTipp();
the console logs
[ 34, 7, undefined, undefined, undefined, undefined ]
[ 1, 2, 3, 4, 5, 6 ]
There were three problems:
If you want to remove one item of an array you have to splice it by the items index and give a deletecount.
In your case: numbers.splice(randomNum, 1);
You have to use Math.floor instead of Math.round, because Math.floor always down to the nearest integerer, while Math.round searches for the nearest integer wich could be higher than numbers.length.
After removing one item the length of the array has been changed. So you have to multiply by numbers.lenght instead of 45.
In your case: var randomNum = Math.floor(Math.random()* numbers.length);
"use strict";
var numbers = [];
for(var x = 1; x < 46; x++){
numbers.push(x);
}
function LottoTipp(){
var result = [];
for(var i = 0; i < 6; i++){
var randomNum = Math.floor(Math.random()* numbers.length);
var pushed = numbers[randomNum];
result.push(pushed);
numbers.splice(randomNum, 1);
}
return console.log(result) + console.log(numbers);
}
LottoTipp();
If you only want an array with random unique numbers I would suggest doing it like this:
<script>
var array = [];
for(i = 0; i < 6; i++) {
var number = Math.round(Math.random() *45);
if(array.indexOf(number) == -1) { //if number is not already inside the array
array.push(number);
} else { //if number is inside the array, put back the counter by one
i--;
}
}
console.log(array);
</script>
There is no issue with the console statement the issue is that you are modifying the numbers array in your for loop. As you are picking the random number between 1-45 in this statement:-
var randomNum = Math.round(Math.random()* 45);
and you expect that value would be present in the numbers array at that random index. However you are using array.splice() and providing only first parameter to the function. The first parameter is the start index from which you want to start deleting elements, find syntax here. This results in deleting all the next values in the array.Therefore if you pick a random number number say.. 40, value at numbers[40] is undefined as you have deleted contents of the array.
if you want to generate unique set of numbers follow this post.
hope it helps!
Just add the number in the result if it is unique otherwise take out a new number and then sort it. Here is an implementation:
let result = []
while(result.length < 6) {
let num = Math.round(Math.random() * 45);
if(!result.includes(num)) {
result.push(num);
}
}
result.sort((a,b) => {
return parseInt(a) - parseInt(b);
});
console.log(result);
What is the simplest way to get 50 random unique elements from an array of 1000 elements ?
text = new Array();
for(i=0;i<1000;i++){ text[i]=i; } //array populated
// now I need to get 50 random unique elements from this array.
The obvious (to me) way is to shuffle the array, then take the first fifty elements. This question has a good way to shuffle an array, and you can then slice the first fifty elements. This guarantees the elements will be unique.
So, using the function there:
fisherYates(text);
text = text.slice(0, 50);
Good algorithms explained in this topic (in C but you can easily to do same in JS)
Look into the Fisher-Yates algorithm, I think this will work for you.
This assumes you mean random indexes and not indexes with unique values.
One way is to copy the array and prune off the ones you use:
function getRandomIndexes( arr, cnt){
var randomArr = [],
arrCopy = arr.slice(),
i,
randomNum ;
for (i=0;i<arrCopy.length;i++) {
randomNum = Math.floor( arrCopy.length * Math.random());
randomArr = randomArr.concat( arrCopy.splice(randomNum ,1) );
}
return randomArr;
}
var myNums = [], i, randSet;
for (i=0;i<10;i++){
myNums.push(i);
}
randSet = getRandomIndexes(myNums, 5);
Another way is to keep track of the indexes you use and keep looking until you find one you did not use. I find the while loop to be scary, and personally would not use this solution if random indexes needed approaches close to the array length.
function getRandomIndexes( arr, cnt){
var randomArr = [],
usedNums = {},
x;
while (randomArr.length<cnt) {
while (usedNums[x]===true || x===undefined) {
x = Math.floor( Math.random() * arr.length);
}
usedNums[x] = true;
randomArr.push( arr[x] );
}
return randomArr;
}
var myNums = [], i, randSet;
for (i=0;i<10;i++){
myNums.push(i);
}
randSet = getRandomIndexes(myNums, 5);
In case you meant unique values:
Demo
var old_arr = [0,1,2,3,4,5,6,7,8,9], new_array = [];
for (var i = 0; i < 5; i++) {
var rand_elem = old_arr[Math.floor(Math.random() * old_arr.length)];
if (arrIndex(old_arr[rand_elem], new_array) == -1) {
new_array.push(rand_elem);
} else {
i--;
}
}
function arrIndex(to_find, arr) {//own function for IE support
if (Array.prototype.indexOf) {
return arr.indexOf(to_find);
}
for (var i = 0, len = arr.length; i < len; i++) {
if (i in arr && arr[i] === to_find) {
return i;
}
}
return -1;
}
In case you meant unique indexs:
Generate random indexes and store the indexes in an array and make checks to prevent duplicates
Start removing the elements of the array after you get them, (you might have problems if you cache the length, so don't)
var arr = [];
while(arr.length < 51){
var ind = Math.floor(Math.random()*1000);
if(!(ind in arr))
arr.push(ind)
}
You'll have 50 random unique numbers in the array arr, which you could use as index
EDIT:
As #ajax333221 mentioned, the previous code doesn't do to get unique elements from the array, in case it contains duplicates. So this is the fix:
var result_arr = [];
while(result_arr.length < 51){
var ind = Math.floor(Math.random()*1000);
if(text[ind] && !(text[ind] in result_arr))
result_arr.push(text[ind]);
}
Being 'text' the array populated with 1000 values
Math.random() * 1000;
Generate 50 random numbers and use them as the position in the array.
How can I arrange an array like a gaussian function, meaning max values in the middle, min values in edges?
e.g.
var Array = [5,2,7,4,1]
will output the following array:
[1,4,7,5,2]
I didn't used underscore functions but you can use equivalent function from underscore/lodash to shorten code.
Steps:
Sort the array in descending order
Iterate over array and add the elements from sorted array at the start and end alternately
var arr = [5, 2, 7, 4, 1];
var sortedArr = arr.sort(function(a, b) {
return b - a;
});
var gaussianArr = [];
sortedArr.forEach(function(e, i) {
if (i % 2) {
gaussianArr.push(e);
} else {
gaussianArr.unshift(e);
}
});
console.log(gaussianArr);
document.write(gaussianArr);
Want underscore solution?
Here you go. fiddle. You won't see much difference between Vanilla JS solution and underscore solution(as the logic is same, only different syntax).
Here is the logic.
function gSort(arr) {
var _a = arr.slice()
_a.sort(function(a,b){return a-b});
_a.reverse();
var _isstart = false;
var _out = [];
for (var i = 0; i < _a.length; i++) {
if (i%2) {
_out.push(_a[i])
}else{
_out.splice(0,0,_a[i]); //You can use _out.unshift(_a[i]); also
}
}
return _out;
}
var array = [5,2,7,4,1]
console.log(gSort(array));
I need to iterate from 0 to 30, but I want to do this with help of forEach:
new Array(30).forEach(console.log.bind(console);
Of course this does not work, therefor I do:
new Array(30).join(',').split(',').forEach(console.log.bind(console));
Is there other ways to fill empty arrays?
Actually, there's a simple way to create a [0..N) (i.e., not including N) range:
var range0toN = Object.keys(Array.apply(0,Array(N)));
Apparently Object.keys part can be dropped if you only want to get a proper array of N elements.
Still, like others said, in this particular case it's probably better to use for loop instead.
if you want all of item have same value, do this
var arrLength = 4
var arrVal = 0
var newArr = [...new Array(arrLength)].map(x => arrVal);
// result will be [0, 0, 0, 0]
You could try using a for loop. new Array is not a best practise
var index, // we use that in the for loop
counter, // number of elements in array
myArray; // the array you want to fill
counter = 30;
myArray = [];
for (index = 0; index < counter; index += 1) {
myArray[index] = [];
/*
// alternative:
myArray.push([]);
// one-liner
for (index = 0; index < counter; index += 1) myArray.push([]);
*/
}
If you simply want to iterate, then use for loop like this
for (var i = 0; i < 30; i += 1) {
...
...
}
Actually, if you are looking for a way to create a range of numbers, then you can do
console.log(Array.apply(null, {length: 30}).map(Number.call, Number));
It will create numbers from 0 to 29. Source : Creating range in JavaScript - strange syntax
If you insist foreach
var data = [1, 2, 3];
data.forEach(function(x) {
console.log(x);
});