How to summize every second number in an Array? - javascript

I'm having trouble summize every second/other number in an Array in Javascript. Any suggestions? (Using Norwegian functions, sorry for that!)
Such as: 2, 4, 6, 8, 10 = 30..
My function for the second/other number is
function tall(nummer) {
var tall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
if (nummer == 5) {
partall = tall.filter((_,i) => i&1);
document.getElementById("tall").innerHTML = partall;
}
and for the final sum:
if (nummer == 9) {
partall = tall.filter((_,i) => i&1);
partall += tall;
document.getElementById("tall").innerHTML = partall;
}

Try the following:
var tall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
let sum = 0;
for (let i = 0; i < tall.length; i += 2){
sum += tall[i];
}
console.log(sum)
Instead of loop over all the number you increment i by 2 thus only looping over the odd numbers.

The simplest way I can see is to use reduce (good for summing) and just don't add in the values for the indexes you don't want to contribute to the sum:
const tall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const sum = tall.reduce((sum, val, i) => sum + (i & 1 ? val : 0), 0);
console.log(sum);
or
const tall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const sum = tall.reduce((sum, val, i) => (i & 1 ? sum + val : sum), 0);
console.log(sum);

Array.prototype.reduce is certainly the way to go here:
var sum = [0,1,2,3,4,5,6,7,8,9,10].reduce((sum, n, i) => {
if (i % 2 === 0)
sum += n;
return sum;
}, 0);
console.log(sum);

Related

JS Number of occurences in a sequence is a prime number

I have two arrays (X and Y) and I need to create array Z that contains all elements from array X except those, that are present in array Y p times where p is a prime number.
I am trying to write this in JS.
For Example:
Array X:
[2, 3, 9, 2, 5, 1, 3, 7, 10]
Array Y:
[2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
Array Z:
[2, 9, 2, 5, 7, 10]
So far I have this:
const arrX = [2, 3, 9, 2, 5, 1, 3, 7, 10]
const arrY = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
const arrZ = []
const counts = [];
// count number occurrences in arrY
for (const num of arrY) {
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
// check if number is prime
const checkPrime = num => {
for (let i = 2; i < num; i++) if (num % i === 0) return false
return true
}
console.log(counts[10]);
// returns 4
Any hint or help appreciated. Thanks!
You're on the right track. counts should be an object mapping elements in arrY to their number of occurrences. It's easily gotten with reduce.
The prime check needs a minor edit, and the last step is to filter arrX. The filter predicate is just a prime check on the count for that element.
// produce an object who's keys are elements in the array
// and whose values are the number of times each value appears
const count = arr => {
return arr.reduce((acc, n) => {
acc[n] = acc[n] ? acc[n]+1 : 1;
return acc;
}, {})
}
// OP prime check is fine, but should handle the 0,1 and negative cases:
const checkPrime = num => {
for (let i = 2; i < num; i++) if (num % i === 0) return false
return num > 1;
}
// Now just filter with the tools you built...
const arrX = [2, 3, 9, 2, 5, 1, 3, 7, 10]
const arrY = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
const counts = count(arrY);
const arrZ = arrX.filter(n => checkPrime(counts[n]));
console.log(arrZ)

Comparing Elements Values In An Array, and returning Boolean

Can anyone help I am nearly there I can get the code to return true for the first 2 test below, but not return false for the next 2 tests, what I need to do is to check that all the numbers in the array are in ascending order so every element number is greater than the last for the length of the array. Any ideas? Kind regards Jon.
Test.expect(inAscOrder([1, 2, 4, 7, 19])
Test.expect(inAscOrder([1, 2, 3, 4, 5])
Test.expect(!inAscOrder([1, 6, 10, 18, 2, 4, 20])
Test.expect(!inAscOrder([9, 8, 7, 6, 5, 4, 3, 2, 1])
function inAscOrder(arr) {
let result = false;
for (let i = 0; i <= arr.length; i++) {
for (let k = 0; k <= arr.length; k++) {
if (arr[i] < arr[k+1]) {
result = true;
}
}
}
return result;
}
You were very close to answer
function inAscOrder(arr) {
let result = true;
for (let i = 0; i <= arr.length; i++) {
if (arr[i] > arr[i+1]) {
result = false;
break;
}
}
return result;
}
Try this,
You can use the functional way instead.
const inAscOrder = arr => arr.slice(1).every((elem,i) => elem > arr[i]);
console.log(inAscOrder([1,2,5]));
The easiest way to compare two arrays, is to convert them to a strings and then compare the strings.
const isAscending = (arr) => arr.join("") == arr.sort((a, b) => a - b).join("");
console.log(isAscending([1, 2, 4, 7, 19]));
console.log(isAscending([1, 2, 3, 4, 5]));
console.log(isAscending([1, 6, 10, 18, 2, 4, 20]));
console.log(isAscending([9, 8, 7, 6, 5, 4, 3, 2, 1]));
For every element in the array, return true if it's the first element or it's greater than the previous element.
const isAscending = (arr) => arr.every((el, i, arr) => i === 0 || el > arr[i - 1]);
console.log(isAscending([1, 2, 4, 7, 19]));
console.log(isAscending([1, 2, 3, 4, 5]));
console.log(isAscending([1, 6, 10, 18, 2, 4, 20]));
console.log(!isAscending([9, 8, 7, 6, 5, 4, 3, 2, 1]));

finding a subset of an array centred on a given item [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Am trying to find a better way to return a range of array values from an existing array.
For an list/array of numbers, say:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I want to select a range of 5 numbers centred around the a given number x.
(Psuedocode since I guess i'm really referring to array indexes here.. values don't matter just the position)
So if x is 4, we can return a range centred on that:
[2, 3, 4, 5, 6]
But if x is 2, we cannot centre the range, so we'd have to do our best and return:
[1, 2, 3, 4, 5]
... Not centered, but atleast we have returned 5 numbers.
Similarly if x is 10:
[5, 6, 7, 8, 9, 10]
... 10 is the limit, so cannot centre, so the 5 numbers are pushed backwards.
I've got this working in some JS code, but it feels like too much code with too many conditionals.
Wondering if there is any known method or algorithm that can help?
You can do something like this.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function findSubset(arr, item) {
// check index
var index = arr.indexOf(item);
// if element not found then return
if (index == -1) return;
// if element is at starting position
// then return first 5 element
if (index < 3)
return arr.slice(0, 5);
// if elements at ending position
// then return last 5 elements
if (index > arr.length - 4)
return arr.slice(-5);
// otherwisse return elements based on the index
// within the required range
return arr.slice(index - 2, index + 3);
}
console.log(
findSubset(arr, 1),
findSubset(arr, 10),
findSubset(arr, 5),
findSubset(arr, 9),
findSubset(arr, 3)
)
A generic solution with a varying count.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function findSubset(arr, item, count = 5) {
var index = arr.indexOf(item),
// calculate floor and ceil value for comparison
// and getting subset array
f = Math.floor(count / 2),
c = Math.ceil(count / 2);
if (index == -1) return;
if (index < c)
return arr.slice(0, count);
if (index > arr.length - c - 1)
return arr.slice(-count);
return arr.slice(index - 2, index + c);
}
console.log(
findSubset(arr, 1, 3),
findSubset(arr, 10, 7),
findSubset(arr, 5, 1),
findSubset(arr, 9, 4),
findSubset(arr, 8, 1),
findSubset(arr, 7, 3),
findSubset(arr, 3, 9)
)
You could move the found index by subtracting the half size and take a max value for negative indices and a min value for indices which are greater than the array length minus the size of the wanted sub array.
value array index adj max min
----- ------------------------------ ----- --- --- ---
v
2 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 1 -1 0 0
[ ]
v
5 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 4 2 2 2
[ ]
vv
10 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 9 7 7 5
[ ]
function getSub(array, value, size) {
var index = array.indexOf(value) - (size - 1) / 2,
max = Math.max(index, 0),
min = Math.min(max, array.length - size);
return array.slice(min, min + size);
}
console.log(getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2, 5));
console.log(getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5, 5));
console.log(getSub([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10, 5));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Recipe of the below algorithm :
Create subset s of max length a.length.
Calculate starting index that is index of x minus half the length of s.
Adjust starting index to prevent index overflow.
Copy s.length items from a to s.
Return s.
Array s is guaranteed to be contained in array a since s is never bigger than a.
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function subset (a, x, n) {
var s = new Array(Math.min(a.length, n));
var j = a.indexOf(x) - Math.floor(s.length / 2);
// overlap to the left : [.[1]2 3 4]
if (j < 0) {
j = 0;
}
// overlap to the right : [1 2 3[4].]
else if (j > a.length - s.length) {
j = a.length - s.length;
}
for (var i = 0; i < s.length; i++) {
s[i] = a[j + i]
}
return s;
}
console.log("x = 2, n = 4, s =", subset(a, 2, 4).join(","));
console.log("x = 9, n = 4, s =", subset(a, 9, 4).join(","));
console.log("x = 5, n = 4, s =", subset(a, 5, 4).join(","));
console.log("x = 2, n = 5, s =", subset(a, 2, 5).join(","));
console.log("x = 9, n = 5, s =", subset(a, 9, 5).join(","));
console.log("x = 5, n = 5, s =", subset(a, 5, 5).join(","));
console.log("x = 5, n = 20, s =", subset(a, 5, 20).join(","));
However, hard to know if it's shorter than your own code since you didn't provide it :-|

Split javascript array of numbers into ranges

I have an array such as:
[16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12]
That I would like split into 6 different arrays based on ranges 1-4, 5-8, 9-12, 13-16, 17-20, 21-24.
What is the simplest way to do this with javascript?
You could use an interval for assigning the numbers to a specific slot.
var array = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12],
interval = 4,
result = array.reduce(function (r, a) {
var slot = Math.floor((a - 1) / interval);
(r[slot] = r[slot] || []).push(a);
return r;
}, []);
console.log(result);
The solution using Array.prototype.filter() function:
var list = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12], i
result = [];
// considering ranges `1-4, 5-8, 9-12, 13-16, 17-20, 21-24`
for (i = 1; i < 24; i+= 4) {
result.push(list.filter(function(d){
return ((i+4 > d) && d >= i); // check if the number between lower and upper bound
}));
}
console.log(result);
Simplest answer:
var numbers = [16, 20, 1, 4, 6, 8, 9, 22, 18, 14, 13, 12];
var array1 = []; // range 1-4
var array2 = []; // range 5-8
for(var i=0; i< numbers.length; i++) {
if(numbers[i]>= 1 && numbers[i] <= 4) {
array1[i] = numbers[i]
} else if(numbers[i]>= 5 && numbers[i] <= 8) {
array2[i] = numbers[i]
}
//... continue for remaining ranges
}

Numbering every number

i want to put number every number using jquery or javascript:
If i input this number:
1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 9, 10 and so on
then my expected output is:
1.1, 1.2, 1.3, 2.1, 3.1, 4.1, 5.1, 5.2, 5.3, 6.1, 7.1, 8.1, 8.2, 9.3, 10.1 and so on
var arr = [1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 9, 10];
var newArr = [arr[0] + ".1"];
var n = 1;
for (var i = 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1]) {
n++;
}
else {
n = 1;
}
newArr.push(arr[i] + "." + n);
}
console.info(newArr);
This does want you want:
var arr = [1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 9, 10];
var newarr = []; check = 0; count = 0;
for(i=0; i<arr.length; i++){
if(check != arr[i]){ count = 1; check = arr[i]; } else { count++; }
newarr.push(check+'.'+count);
}
console.log(newarr);
Ofcourse the numbers should be grouped together, else you will get 1.1,1.2,2.1,3.1,1.1,1.2,5.1 Then you should first do arr.sort()

Categories

Resources