Check if any number in array is bigger than given number Javascript - javascript

I have this function which finds the avarage in the array :
const findAvarage = (a,b,c,d) =>{
let total = 0;
let numbers = [a,b,c,d];
for(let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
let avg = total / numbers.length;
console.log("avg",avg)
}
findAvarage(2,2,6,10);
Now I need to find out index of number in the array which is bigger than the avarage number,Any suggestions please?

You can achieve this with the find() method:
const array1 = [2, 2, 6, 10];
const found = array1.find(element => element > findAvarage(2,2,6,10));
console.log(found);
If you want to get back the index of the element, use findIndex() instead
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

I saw lot of answers, but none of them has improved the find average function, it is limited to only four digits and it doesn't return the result, and even for finding the biggest number than the average, both should be dynamic
const findAvarage = (...nums) => nums.reduce((a, b) => a + b) / nums.length || 0;
const getBiggestNumberThanTheAverage = (...nums) => {
let average = findAvarage(...nums);
return nums.find(num => num > average);
}
console.log(getBiggestNumberThanTheAverage(2, 2, 6, 10));
console.log(getBiggestNumberThanTheAverage(3, 2, 7));
console.log(getBiggestNumberThanTheAverage(7, 5, 9, 10, 18, 8, 1, 6));

const findAvarage = (a,b,c,d) =>{
let total = 0;
let numbers = [a,b,c,d];
for(let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
let avg = total / numbers.length;
return avg;
}
let arr = [2, 2, 6, 10];
arr=arr.filter(element => element > findAvarage(2,2,6,10));
console.log(arr); //this shows all numbers > average
//now to see the highest number
var yourAnswer = arr.sort()[arr.length-1];
console.log("Your answer is "+yourAnswer);
this is just the running version

Related

Why is answer NaN?

I have five positive integers, I want to find the minimum and maximum values that can be calculated by summing exactly four of the five integers. index of array is number, but when I print answer, it's NaN
var sumArr = []
var sum = 0
function miniMaxSum(arr) {
// Write your code here
for(let i = 0; i < arr.length; i++){
sumArr.push(arr.filter(item => item !== arr[i]).reduce((previousValue, currentValue) => previousValue + currentValue, sum))
}
console.log(Math.min(sumArr), Math.max(sumArr))
}
let sides = [1, 2, 3, 4, 5];
const result = miniMaxSum(sides);
Because you're passing an array, those functions are expecting numbers instead. Take a look at Math
You can spread those arrays as follows:
var sumArr = []
var sum = 0
function miniMaxSum(arr) {
// Write your code here
for(let i = 0; i < arr.length; i++){
sumArr.push(arr.filter(item => item !== arr[i]).reduce((previousValue, currentValue) => previousValue + currentValue, sum))
}
console.log(Math.min(...sumArr), Math.max(...sumArr))
}
let sides = [1, 2, 3, 4, 5];
const result = miniMaxSum(sides);

JS: restart loop with a updated index number

Is there a possibility to restart this loop with a new index number:
let ar = [1, 1, 2, 1, 2, 1, 3, 2, 3, 1];
let sortedArray = ar.sort();
let sameNumbersArray = [];
let numberOfSameNumbers = 0;
let lastIndexNumber = 0;
for (i = lastIndexNumber; i < sortedArray.length; i++) {
if (sortedArray[i] == sortedArray[i + 1]) {
const sameNumber = sortedArray[i];
sameNumbersArray.push(sameNumber);
} else {
break;
}
let lastIndexFromNumberArray = [];
lastIndexFromNumberArray.push(sameNumbersArray.length);
lastIndexFromNumberArray.push(3);
lastIndexFromNumberArray.push(2);
lastIndexNumber = lastIndexFromNumberArray.reduce(function (a, b) {
return a + b;
}, 0);
So basically that the loop (lastIndexNumber) starts with index[0], but then restarts with index[5] and index[7].
How would one add this extra loop?
I'm not 100% clear on the aim here. Are you able to elaborate on the desired result of the above?
It looks like you want to get an array of the unique numbers and perhaps the number of unique numbers from the source array?
If so, here's another way which might be cleaner:
let ar = [1, 1, 2, 1, 2, 1, 3, 2, 3, 1];
let sortedArray = ar.sort();
let newSameNumbersArray = unique(sortedArray);
//array of unique numbers:
console.log(newSameNumbersArray);
//count of unique numbers:
console.log(newSameNumbersArray.length);
function unique(array) {
return Array.from(new Set(array));
}
This is based on this answer: https://stackoverflow.com/a/44405494/4801692
That said, you can directly set the value of i and use continue to move to the 'next' iteration.
i = 5;
continue;
This is bad though as you are in danger of feeding i a lower number and getting stuck in an infinite loop. If you can explain the requirement a little more I might be able to suggest something better.
you can do such thing to find the pairs
let ar = [10, 10, 10, 20, 20, 10 ,30, 20 ,30]
function findPair(ar) {
let counts = {};
let count = [];
let sum = 0;
for(let i = 0; i < ar.length; i++){
let item = ar[i]
counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
}
count = Object.values(counts);
for(let i = 0; i < count.length; i++){
if(count[i] >= 2){
sum += Math.floor(count[i]/2)
}
}
console.log(sum)
}
findPair(ar)

Mini-Max Sum HACKERHANK JS, why isn't working?

I don't know what's wrong, my function miniMaxSum isn't summing 1+3+4+5. At the end, the result array turns into this [ 14, 12, 11, 10 ], when it should looks like this [ 14, 13, 12, 11, 10 ]
function miniMaxSum(arr) {
let results = [];
let actualValue = 0;
let skipIndex = 0;
for (let i = 0; i < arr.length; i++) {
//skip actual index
if (i == skipIndex) continue;
actualValue += arr[i];
//restart the loop
if (i == arr.length - 1) {
skipIndex++;
results.push(actualValue);
actualValue = 0;
i = 0;
}
}
console.log(results);
console.log(Math.min(...results), Math.max(...results));
}
console.log(miniMaxSum([1, 2, 3, 4, 5]));
You're over-complicating your algorithm by trying to check whether you should add the current number to the overall sum or not. Instead, all you need to do is run a loop over your array, to sum up all your elements in your array. This will give you the total sum of all your elements. Then, again, iterate through your array. For each element in your array subtract it from the sum you just calculated and push it into a new array. This will give you the sum if you were to not use the number in the ith position. You can then find the min/max of this using JavaScript's Math.min and Math.max functions.
Here is an example using .reduce() and .map() to calculate the final result:
const miniMaxSum = arr => {
const sum = arr.reduce((s, n) => n+s, 0)
const results = arr.map(n => sum - n);
return [Math.min(...results), Math.max(...results)];
}
const [min, max] = miniMaxSum([1, 2, 3, 4, 5]);
console.log(min, max);
If you prefer standard for loops, here is an implementation of the above in a more imperative style:
const miniMaxSum = arr => {
let sum = 0;
for(let i = 0; i < arr.length; i++) { // sum all elements
sum += arr[i];
}
let results = [];
for(let i = 0; i < arr.length; i++) {
results[i] = sum - arr[i]; // sum minus the current number
}
return [Math.min(...results), Math.max(...results)];
}
const [min, max] = miniMaxSum([1, 2, 3, 4, 5]);
console.log(min, max);
Assuming you're talking about this question.
Whenever you want to restart the loop, you're setting i=0 but observe that you also have increment statement i++ in for loop so, effectively i starts from 1, not 0. You need to set i=-1 so that i=-1+1 = 0 in subsequent iteration. After doing this, you need to handle a corner case. When skipIndex==arr.length-1, check if i == arr.length-1. If yes, do results.push(actualValue); for the last value and then for loop terminates because i < arr.length is false in next iteration.
Code:
function miniMaxSum(arr) {
let results = [];
let actualValue = 0;
let skipIndex = 0;
for (let i = 0; i < arr.length; i++) {
//skip actual index
if (i == skipIndex){
if(i == arr.length - 1)
results.push(actualValue);
continue;
}
actualValue += arr[i];
//restart the loop
if (i == arr.length - 1) {
skipIndex++;
results.push(actualValue);
actualValue = 0;
i = -1;
}
}
console.log(results);
console.log(Math.min(...results), Math.max(...results));
}
miniMaxSum([1, 2, 3, 4, 5]);
Output
[ 14, 13, 12, 11, 10 ]
10 14

Sort Array to 1st min, 1st max, 2nd min, 2nd max, etc

Write a JS program to return an array in such a way that the first element is the first minimum and the second element is the first maximum and so on.
This program contains a function which takes one argument: an array. This function returns the array according to the requirement.
Sample Input: array=[2,4,7,1,3,8,9]. Expected Output: [1,9,2,8,3,7,4].
const arrsort=(arr)=>{
return arr.sort(function(a, b){return a - b});
}
const test=(arr)=>{
arr=arrsort(arr);
var arr2=[];
var j=0;
var k=arr.length-1;
for (var i=0;i<arr.length-1;i++){
if(i%2===0){
arr2.push(arr[j]);
j++;
}
else{
arr2.push(arr[k]);
k--;
}
}
return arr2;
}
Instead of using two indices, you could shift and pop the values of a copy of the sorted array.
var array = [2, 4, 7, 1, 3, 8, 9]
const arrsort = arr => arr.sort((a, b) => a - b);
const test = (arr) => {
var copy = arrsort(arr.slice()),
result = [],
fn = 'pop';
while (copy.length) {
fn = { pop: 'shift', shift: 'pop' }[fn];
result.push(copy[fn]());
}
return result;
}
console.log(test(array));
You can first sort() the array in ascending order and then loop through half of the array. And push() the values at corresponding indexes.
let arr = [2,4,7,1,3,8,9];
function order(arr){
let res = [];
arr = arr.slice().sort((a,b) => a-b);
for(let i = 0; i < Math.floor(arr.length/2); i++){
res.push(arr[i],arr[arr.length - 1 - i]);
}
return arr.length % 2 ? res.concat(arr[Math.floor((arr.length - 1)/2)]) : res;
}
console.log(order(arr))
You could sort the array, then copy and reverse and push to another array
const a = [2,4,7,1,3,8,9];
a.sort();
const b = a.slice().reverse();
const res = [];
for (let i = 0; i < a.length; i++) {
if (res.length < a.length) res.push(a[i]);
if (res.length < a.length) res.push(b[i]);
}
console.log(res);
Or use a Set
const a = [2,4,7,1,3,8,9];
a.sort();
const b = a.slice().reverse();
const res = new Set();
a.forEach((e, i) => (res.add(e), res.add(b[i])));
console.log(Array.from(res));
There are many ways are available to do this. And my solution is one of themm i hope.
Find max and min value, push them into another array. And delete max, min from actual array.
let array=[2,4,7,1,3,8,9];
let finalArray = [];
let max, min;
for(let i = 0; i < array.length; i++) {
max = Math.max(...array);
min = Math.min(...array);
finalArray.push(min);
finalArray.push(max);
array = array.filter(function(el) {
return el != max && el != min;
})
}
console.log(finalArray);
After sorting array this would work
myarr = [1,2,3,4,5,6];
let lastindex = myarr.length-1;
for(let i = 1 ; i <= myarr.length/ 2; i = i+2) {
ele = myarr[i];
myarr[i] = myarr[lastindex];
myarr[lastindex] = ele;
lastindex--;
}
Final Output will be: [1, 6, 3, 5, 4, 2]
You can use two iterators after sorting your array, one goes ascending and the other goes descending, until they cross each other.
Here's the code:
const array = [2, 4, 7, 1, 3, 8, 9];
const test = arr => {
const result = [];
const sortedArr = array.sort((a, b) => a - b);
for (let i = 0, j = sortedArr.length - 1; i <= j; i++, j--) {
result.push(sortedArr[i]);
i == j || result.push(sortedArr[j]);
}
return result;
};
console.log(test(array));
You can easily achieve the result using two pointer algorithm
function getValue(arr) {
const result = [];
let start = 0,
end = arr.length - 1;
while (start < end) result.push(arr[start++], arr[end--]);
if (start === end) result.push(arr[start]);
return result;
}
const array = [2, 4, 7, 1, 3, 8, 9];
const sorted = array.sort();
console.log(getValue(sorted));

loop over array, but not every element

I would like to iterate over the array and getting an average from 5 next elements, not from the whole array. I try to do it by code bellow, but it doesn´t work. I appreciate any kind of help or suggestions.
function standardDeviation(array) {
let newArray = [];
for (let i = 0; i < array.length; i++) {
let tempArray = [];
const arrAvg = tempArray =>
tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
newArray += tempArray;
for (let j = array[i]; (j = array[i + 5]); i++) {
tempArray += array[j];
}
}
console.log(newArray);
return newArray;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
standardDeviation(arr);
You could slice a given array and take only five elements for getting an average.
function standardDeviation(array) {
const arrAvg = tempArray => tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
return array.map((_, i, a) => arrAvg(a.slice(i, i + 5)));
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(standardDeviation(arr));
You could try using the slice() function of array element.
// simulated loop index
var curr_index_pos = 3;
// entire array
var array_full = [1,2,3,4,5,6,7,8,9,10];
// array with 5 next values from "curr_index_pos"
var array_5 = array_full.slice(curr_index_pos,curr_index_pos+5);
var sum = 0;
for( var i = 0; i < array_5.length; i++ ) {
sum += parseInt( array_5[i] );
}
var avg = sum/array_5.length;
console.log("array_5", array_5);
// [4,5,6,7,8]
console.log("sum", sum);
// 30
console.log("avg", avg);
// 6

Categories