Related
this function return the sum of all elements in the array
const array = [4, 7, 24, 7, 0, 10];
const number = 7;
function addTheSameNumbers1(number, array) {
let count = array.length;
for (let i = 0; i < count; i++) {
if (array[i] === number) {
return array.reduce((a,b) => a + b, 0);
}
}
return null;
}
console.log(addTheSameNumbers1(number, array));```
Your reduce() is summing all the values. This is how to sum a single number:
const array = [4, 7, 24, 7, 0, 10];
const number = 7;
function addTheSameNumbers1(number, array) {
return array.reduce((accum, val) =>
val === number ? accum + val : accum
, 0);
}
const result = addTheSameNumbers1(number, array);
console.log(result);
If I understand you correctly, you want to get the sum of the elements that have values which are the same to the length of their parent array. This code should do it.
const filterAndSum = (numbers, query) => {
return numbers
.filter((n) => n === query)
.reduce((n, total) => total + n, 0);
};
console.log(filterAndSum([1,2,3,4,5,4,3,2,1,2,3,2,1], 3))
First, it filters the elements which are not equal to the length of the parent array then gets the sum of the remaining elements. Note that validation is not implemented here, but I believe you could easily do that.
You can get the count the occurrence of variable and the multiple with the number
<script>
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
const array = [4, 7, 24, 7, 0, 10];
const number = 7;
var accur = countOccurrences(array, number);
console.log(accur);
console.log(accur * number);
</script>
An alternative to reduce is to use a simple for/of loop to iterate over the numbers, and then add any found numbers to a sum variable.
const array = [4, 7, 24, 7, 0, 10];
const number = 7;
function sumTheSameNumber(n, arr) {
let sum = 0;
for (let i of arr) {
if (i === n) sum += i;
}
return sum;
}
console.log(sumTheSameNumber(number, array));
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
I am trying to add all array elements with basic for loop for some reason, my variable 'result' return NaN.
let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
for (let i = 0; i <= arr.length; i++) {
result = arr[i] + result
}
console.log(result)
}
arraySum(array)
Please use basic looping to answer, I tried .reduce method but want to use basic loops
Thank you
Your condition of i <= arr.length should be using i < arr.length
The length of the array is 5 but the index of the last number is 4, so you don't want <= there.
let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
for (let i = 0; i < arr.length; i++) {
result = arr[i] + result
}
console.log(result)
}
arraySum(array)
Length start at 1, so you need to set < operator in your loop :
let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
for (let i = 0; i < arr.length; i++) {
result = arr[i] + result
console.log(result)
}
console.log("result = ", result)
}
arraySum(array)
The reason for this problem is that the array has a length of 5 and the last index is 4. When the loop is at index = 5 there is no element at position 5. The result will therefore be undefined. To avoid this problem, the for loop should be like this:
for (let i = 0; i < arr.length; i++)
or
for(const i in arr)
You put '<=' in the for loop but you must use just '<'.
if array = [1,2,3] then length = 3 but array index goes from 0 to 2 not 3
you could try, if simple enough:
let array = [1, 2, 3, 4, 5];
let result = 0;
arraySum = (arr) => {
for (let i = 0; i < arr.length; i++) {
result += arr[i]
}
console.log(result)
}
arraySum(array)
the "<=" shoud be placed by "<"
let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
for (let i = 0; i <= array.length; i++) {
result += array[i];
}
console.log(result);
};
arraySum(array);
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));
I'm trying to find the second largest number in an array of numbers, but the greatest number appears twice, so I can't just remove it from the array and select the new highest number.
array = [0, 3, 2, 5, 5] (therefore 3 is the 2nd largest value)
I have this code where I can explicitly return 3, but it wouldn't work on other arrays:
function getSecondLargest(nums) {
var sorted_array = nums.sort(function (a,b) {return a - b;});
var unique_sorted_array = sorted_array.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
return unique_sorted_array[unique_sorted_array.length - 2];
}
return unique_sorted_array[unique_sorted_array.length - 2];
If I wanted to make it more dynamic, is there a way that I could identify the greatest value of the array, then compare that against each iteration of the array?
I was thinking that something along the lines of:
var greatestNum = sortedArray[-1]
while(greatestNum != i) do {
//check for the first number that doesn't equal greatestNum
}
Any help would be appreciated.
You can simply create a Set first and than sort in descending and take the 1st index element
let array = [0, 3, 2, 5, 5]
let op = [...new Set(array)].sort((a,b) => b-a)[1]
console.log(op)
For those who thinks in terms of efficiency. this is the best way IMO
let array = [0, 3, 2, 5, 5]
let max = -Infinity
let secondMax = -Infinity
for(let i=0; i<array.length; i++){
if(array[i] > max){
secondMax = max
max = array[i]
}
}
console.log(secondMax)
I’d recommend doing something more like
const nums = [0, 3, 2, 5, 5];
nums.sort(function (a,b) {return b - a;})
for (let i = 1; i < nums.length; i++) {
if (nums[0] !== nums[i]) {
return nums[i];
}
}
which should be a lot more efficient (especially in terms of memory) than converting to a set and back...
Try this:
var intArray = stringArray.map(nums); // now let's sort and take the second element :
var second = intArray.sort(function(a,b){return b-a})[1];
};
For those who wants to do this using Math.max(). Here's the simplest way to do this.
const getSecondLargest = function (arr) {
const largest = Math.max.apply(null, arr);
for (let i = 0; i < arr.length; i++) {
if (largest === arr[i]) {
arr[i] = -Infinity;
}
}
return Math.max.apply(null, arr);
};
console.log(getSecondLargest([3, 5, 9, 9, 9])); //5
Side note: Math.max() don't take an array, so we have to use Math.max.apply() to pass the array in the function. -Infinity is smaller than any negative finite number.