trying to get a quantity of absent elements in the array [duplicate] - javascript

This question already has answers here:
Why is math.max() returning NaN on an array of integers?
(5 answers)
Closed 5 years ago.
i am trying to handle with an array with non-consecutive numbers . Here is my example var myArray = [2, 4, 6, 8] . absent numbers are 3, 5, 7 and the quantity = 3 . I tried to get it with this function `
function makeArrayConsecutive(myArray) {
return Math.max(myArray) - Math.min(myArray) + 1 - myArray.length;
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));
this must return 3 ... but it returns NaN... whats the issue ?

Here's one solution that I think would work for you:
function makeArrayConsecutive(arr) {
//get the min and max using reduce
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
var min = arr.reduce(function(a, b) {
return Math.min(a, b);
});
//amount of numbers b/t min/max if array had no "gaps"
var deltaDesired = ((max - min) - 1);
//actual amount of numbers b/t min/max in our array
var deltaActual = (arr.length - 2);
return (deltaDesired - deltaActual);
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));

Related

Javascript - Sum two specific array numbers [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I have an array that I need to the following with:
arranged from lowest to highest.
Select the middle two numbers.
Sum the middle two scores.
Am I on the right track?
var numArray = [2, 1, 3, 1, 4, 2];
numArray.sort((a, b) => a - b);
var sum = numArray[2] + numArray[3];
I think Array.reduce can be used somehow?
var sum = numArray[2] + numArray[3]; gives me two numebrs together and not their sum.
How do I do math function sum rather than combined two variables into one?
Edit: DrafsApp for Mac was adding two values "2" and "2" into "22"
I had to change the code to this and it works:
var sum = Number(numArray[2]) + Number(numArray[3]);
The code is returning the sum as expected.
var numArray = [2, 1, 3, 1, 4, 2];
numArray.sort((a, b) => a - b);
//Sorted array - [1, 1, 2, 2, 3, 4]
var sum = numArray[2] + numArray[3];
//sum = 2 + 2
console.log(sum);

How to select the middle of an array?

I thought I could use
$ [1,2,3,4,5].splice((this.length / 2), 1)[0]
but it gives me
$ 1
I tried
$ [1,2,3,4,5].splice(function() { return this[this.length / 2, 1]})
but it gives me
[ 1, 2, 3, 4, 5 ]
I'm looking for a solution that gives me an integer and for even arrays is the lower of the two, e.g.
[1,2,3,4] givees 2
[1,2,3,4,5] gives 3
[1,2,3,4,5,6] gives 3
[1,2,3,4,5,6,7] gives 4
The issue is with this reference. Try this:
console.log(getMiddle([1,2,3,4]));
console.log(getMiddle([1,2,3,4,5]));
console.log(getMiddle([1,2,3,4,5,6]));
console.log(getMiddle([1,2,3,4,5,6,7]));
function getMiddle(arr){
return arr.splice(Math.floor((arr.length-1) / 2), 1)[0]
}
However, As #jonrsharpe 's comment states, splicing a single-element array from an index to the same index plus one then getting the first value in the result creates a redundant array. A better way to get the middle element would be the following:
console.log(getMiddle([1,2,3,4]));
console.log(getMiddle([1,2,3,4,5]));
console.log(getMiddle([1,2,3,4,5,6]));
console.log(getMiddle([1,2,3,4,5,6,7]));
function getMiddle(arr){
return arr[Math.floor((arr.length - 1) / 2)];
}
You should use something like that.
var data, remaining, hold, result;
data = ["1","2","3","4","5","6","7","8", "9"];
remaining = data.length % 2;
hold = Math.floor(data.length / 2);
result = data[(remaining + hold - 1)];
document.write(result);
You could create a prototype for getting the middle element/s.
Array.prototype.middle = function () {
const
half = this.length >> 1,
offset = 1 - this.length % 2;
return this.slice(half - offset, half + 1);
};
console.log([1, 2, 3, 4, 5].middle()); // [3]
console.log([1, 2, 3, 4, 5, 6].middle()); // [3, 4]
console.log([1, 2, 3, 4].middle()); // [2, 3]
.as-console-wrapper { max-height: 100% !important; top: 0; }
You cannot use this as a parameter because this is supposed to be called inside functions, whereas splice accept as parameters integers. If you really want to use this you may use a prototype. Use Math.floor function since arrays indexes only accept integers, and Math.floor rounds up to the lowest integer (ex: Math.floor(2.5) === 2).
Array.prototype.getMiddle = function () {
return this[Math.floor(this.length/2)]
}
console.log([1,2,3,4,5].getMiddle()) // 3
The above function only works when the length of the array is an odd number, since arrays whose length is an even number do not have "middle" element.
If you want to check if the array has a middle
Array.prototype.getMiddle = function () {
return (this.length % 2) ? this[Math.floor(this.length/2)] : null
}
console.log([1,2,3,4,5].getMiddle()) // 3
console.log([1,2,4,5].getMiddle()) // null
Alternative solutions:
var arr = [1,2,3,4,5]
var middleEl = arr[Math.floor(arr.length/2)]
console.log(middleEl) // 3
If you want to use splice
var arr = [1,2,3,4,5]
var middleEl = arr.splice((arr.length / 2), 1)[0]
console.log(middleEl)
If you want a function
console.log(middleEl([1,2,3,4,5])) //3
console.log(middleEl([1,2,4,5])) //null
function middleEl (arr) {
return (arr.length % 2) ? arr[Math.floor(arr.length/2)] : null
}
let arr = [ 1, 2, 3, 4, 5 ]
let len = arr.length;
let mid = Math.floor(len / 2);
console.log(arr[mid]);
// or
console.log(arr.slice(mid, mid + 1));
or if you want the middle two, you can do mid + 2 using a var that tests to see if the length is even.
Why not simply, assuming a.length > 0:
const a = [1, 2, 3, 4, 5]
console.log(a[(a.length - 1) >> 1])
const b = [1, 2, 3, 4, 5, 6]
console.log(b[(b.length - 1) >> 1])
I think this should be a fairly fast way of doing it. The >> operator is an integer shift, which divides the number by two - ignoring decimals.

returning strings instead of numbers [duplicate]

This question already has answers here:
What is the difference between ( for... in ) and ( for... of ) statements?
(18 answers)
Closed 2 years ago.
I'm trying to write a function (onlyOddNumbers) that accepts an array of numbers and returns a new array with only the odd numbers, it's working but the problem is I'm getting strings in the new array instead of numbers, why this happen ?
let oddNumbersOnly=[]
const filter = function (numbers) {
for (number in numbers){
if(number %2 !==0){
oddNumbersOnly.push(number)
}
} return oddNumbersOnly;
};
use for of instead of for in then convert your num to string
const filter = function(numbers) {
let oddNumbersOnly = []
for (let number of numbers) {
if (number % 2 !== 0) {
oddNumbersOnly.push(number.toString())
}
}
return oddNumbersOnly;
};
const arr = [1, 2, 3, 4, 5, 6];
const result = filter(arr)
console.log(result)
let num = [0, 1, 2, 3, 4, 5, 6];
let oddNumbersOnly = num.filter(numb=>numb%2 !==0);
console.log(oddNumbersOnly);
javaScript has an inbuilt es6 filter function. It is shorter and retain the datatype. You may try this.

Mini-Max Sum - Wrong output

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example, if the array is [1, 3, 5, 7, 9]. Our minimum sum is 1 + 3 + 5 + 7 = 16 and our maximum sum is 3 + 5 + 7 + 9 = 24.
function miniMaxSum(arr) {
let max = arr.reduce((a, b) => a + b, 1);
let min = arr.reduce((a, b) => a + b, 0, arr.length - 1);
console.log(min, max);
}
Right now, the output should be 10, 14 if the array is just [1, 2, 3, 4, 5].
The output I am getting is 15, 16.
The max variable should just add everything starting from index 1 no?
And the min variable I'm not sure if you're able to do this, but my thinking was initialize the starting at index 0 and go up to the end of the array but minus 1 index.
How can I correct this?
You need to identify which 4 of the 5 elements are the largest, and which 4 of the 5 elements are the smallest - or, equivalently, identify which one element is the smallest, and which one element is the largest, and subtract those from the sum of all 5 elements:
function miniMaxSum(arr) {
// fullSum: sum of all items in the array
const fullSum = arr.reduce((a, b) => a + b, 0);
// Find smallest value in array
const min = Math.min(...arr);
// Find largest value in array
const max = Math.max(...arr);
console.log(fullSum - max, fullSum - min);
}
miniMaxSum([1, 3, 5, 7, 9]);
miniMaxSum([1, 2, 3, 4, 5]);
Another approach is to use slice and sum the small and and the large end of the array.
function miniMax(arr) {
const sum = a => a.reduce((a, b) => a + b, 0);
// we can skip the sort if we know the input is sorted, but just in case
const sorted = arr.sort((a,b) => a-b)
const min = sum(sorted.slice(0, sorted.length-1)) // sum the small end of the array
const max = sum(sorted.slice(1)) // sum the large end of the array
return { min, max }
}
console.log(miniMax([1, 3, 5, 7, 9]));
console.log(miniMax([1, 2, 3, 4, 5]));
This only works if the numbers are listed in ascending order in the array
function miniMaxSum(arr)
{
let max = arr.reduce((a,c,i)=>i?a+c:0, 0);
let min = arr.reduce((a,c,i,t)=>i?a+t[i-1]:0, 0);
document.write(`${JSON.stringify(arr)} -> min: ${min}, max: ${max} <br>`);
}
miniMaxSum([1, 3, 5, 7, 9]);
miniMaxSum([1, 2, 3, 4, 5]);
It was fun to do ;)

intersection of two arrays which are unique by javascript in simple way [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 4 years ago.
Given two arrays of unequal length:
var array = [1,2,5,1,2,5,5,3];
var array2 = [2,5,5,3,1,10];
How can I find the values common in both arrays? In this case, output should be "1, 2, 5, 3".
While you like to get unique items of common values, you could use a Set for both arrays and filter the unique values.
This proposal returns a different result as the above duplication target.
function getCommon(a, b) {
return [...new Set(a)].filter(Set.prototype.has, new Set(b));
}
var a = [1, 2, 5, 1, 2, 5, 5, 3],
b = [2, 5, 5, 3, 1, 10];
console.log(getCommon(a, b));
In javascript you can use these tow functions
function intersect(a, b) {
return a.filter(Set.prototype.has, new Set(b));
}
function removeDuplicates(arr){
let unique_array = []
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}
var array1=intersect([1,2,5,1,2,5,5,3], [2,5,5,3,1,10]);
console.log(array1);
console.log(removeDuplicates(array1));

Categories