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
}
Related
Can someone please help me understand the differences between these two programs? I was doing this RallyCoding Prep problem and wrote the first program (and it failed). Then I checked what others did to try and understand but it seems to me that the two programs do basically the same thing, written differently. Can someone help me understand why mine fails and the second program works?
Link to problem: https://www.rallycoding.com/problems/205
--My code--
let k = 16;
let length = Math.sqrt(k);
let height = length;
let arr = []
for(let i = 0; i < length; i++){
let row = [];
for(let x = 1; x <= k; x++){
row.push(x);
}
arr.push(row);
}
console.log(arr)
--Their code--
let k = 16
let c = 1;
const r = Math.sqrt(k);
const result = [];
while(c <= k) {
const block = [];
for (let i = 1; i <= r; i++) {
block.push(c);
c++;
}
result.push(block);
}
console.log(result)
I'm certain I'm missing something very obvious. I hope someone can help me understand this. Thank you!
Since the value of k = 16, the inner loop runs 16 times. So, the result produced by your code is
[
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
]
And the result produced by their code is
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
So, you can make these changes in your code to get the desired result.
let k = 16;
let length = Math.sqrt(k);
let height = length;
let arr = []
for(let i = 0; i < length; i++){
let row = [];
for(let x = 1; x <= length; x++){
row.push(x + i * length);
}
arr.push(row);
}
You code produces data like this: [[1, 2, 3], [1, 2, 3], ...]
(Each sub-array starts with 1)
You need to produce: [[1, 2, 3], [4, 5, 6], ...]
(Each sub array continues the sequence of the previous one)
the nested forloop you created loop over 16 times
for(let x = 1; x <= k; x++){ row.push(x); }
because K=16 so it will provide an array with 16 element.
the forloop keep runing intel it finish the job.but in the correction they use a "while" loop because The 'while' loop used only when the number of iteration are not exactly known.the are some diff between the two.
Here's a link you can find more
I need to iterate through the array and multiply a number by 10 if it is greater than or equal to 5. Here is the code:
const timesTenIfOverFive = [23, 9, 11, 2, 10, 6];
for (let i = 0; i < timesTenIfOverFive.length; i++) {
if (i >= 5) {
console.log(timesTenIfOverFive[i] * 10);
} else {
console.log(timesTenIfOverFive[i]);
}
}
console.log(timesTenIfOverFive);
// -> should print [230, 90, 110, 2, 100, 60]
Thanks.
You need to access the element and change it.
const timesTenIfOverFive = [23, 9, 11, 2, 10, 6];
for (let i = 0; i < timesTenIfOverFive.length; i++) {
if(timesTenIfOverFive[i]>=5){
timesTenIfOverFive[i]=timesTenIfOverFive[i]*10;
}
}
console.log(timesTenIfOverFive);
Also since you are mutating the array, i recommend using var or let for that and not const as follows:
var timesTenIfOverFive = [23, 9, 11, 2, 10, 6];
var res = timesTenIfOverFive.map(x=> x>=5?x*10:x);
console.log(res);
Use Array.prototype.map() to create a new Array by mapping over an existing one
const arr = [23, 9, 11, 2, 10, 6];
const timesTenIfOverFive = arr.map(n => n>=5 ? n*10 : n );
console.log(timesTenIfOverFive)
// -> should print [230, 90, 110, 2, 100, 60]
In short, the ?: Ternary Operator does :
n >= 5 ? // is n greater or equal 5 ?
n * 10 : // if true return the multiplication by 10
n // else return the n
For a reusable function:
const timesTenIfOverFive = arr => arr.map(n => n>=5 ? n*10 : n );
console.log(timesTenIfOverFive([23, 9, 11, 2, 10, 6]))
// -> should print [230, 90, 110, 2, 100, 60]
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);
I have an array:
var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
I need to remove each 3rd item from the array and add it to another array.
The final result should be:
var myArray = [12, 11 18, 30, 21, 18];
var secondArray = [13, 51, 20];
How can i do that?
iterate over the array and splice every 3rd element and push to the second array.
var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var secondArray = [];
for (var i = 2; i < myArray.length; i += 2) {
secondArray.push(myArray[i]);
myArray.splice(i, 1);
}
console.info('myArray', myArray)
console.info('secondArray', secondArray)
I do not like example with splicing source array, because splicing is a long operation and in large arrays / multiple operations it will be not so effective. I think you should create new arrays and don't mind.
const arraysList = myArray.reduce((acc, item, index) => {
if ((index + 1) % 3 === 0) {
acc.second.push(item);
} else {
acc.first.push(item);
}
return acc;
}, { first: [], second: [] })
console.log(arraysList.first); // [12, 11 18, 30, 21, 18]
console.log(arraysList.second); // [13, 51, 20]
var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var newArray1 = [];
var newArray2 = [];
myArray.forEach(function(value,index){
if((index + 1) % 3 === 0){
newArray1.push(value);
}
else {
newArray2.push(value);
}
});
console.log(newArray1); // Stores element at index 3 in the original array
console.log(newArray2); // Stores element at index other than 3 in the original array
Array#reduce the original array into 2 new arrays:
const myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
const [without3rdItems, with3rdItems] = myArray.reduce((arrs, n, i) => {
const arr = (i + 1) % 3 ? 0 : 1;
arrs[arr].push(n);
return arrs;
}, [[], []]);
console.log(without3rdItems.join());
console.log(with3rdItems.join());
var a = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var b = [ ];
var l = a.length;
for(i = 2; i < l; i += 2){
b.push(a[i]);
a.splice(i, 1);
l--;
}
console.log("Array a: ", a);
console.log("Array b: ", b);
var set1 = [14, 9, 1, 6, 16],
set2 = [4, 15, 16, 14, 11],
set3 = [16, 10, 2, 3, 8],
set4 = [3, 17, 16, 6, 14],
set5 = [19, 18, 14, 6, 20],
set6 = [6, 15, 8, 7, 2],
set7 = [15, 14, 2, 19, 3],
set8 = [8, 2, 14, 10, 5],
set9 = [11, 6, 8, 10, 18],
set10 = [14, 10, 12, 4, 18],
input = [set1, set2, set3, set4, set5, set6, set7, set8, set9, set10];
// Sort function
function sortFunction(a) {
var len = a.length,
temp, i, j;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
if (a[j] < a[i]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a;
}
// Sorting each sets and finding range of each sets
for (var i = 0; i < len; i++) {
input[i] = sortFunction(input[i]);
minRange.push(Math.min.apply(null, input[i]));
maxRange.push(Math.max.apply(null, input[i]));
}
// Finding the range of input
var minimum = Math.min.apply(null, minRange);
var maximum = Math.max.apply(null, maxRange);
var range = maximum - minimum + 1;
// Matrix table function
var tableArray = [];
function table() {
for (var i = 0; i < len; i++) {
for (var j = 0; j < range; j++) {
if (input[i][j] == j) {
tableArray[i].push(input[i][j]);
} else {
tableArray[i].push(0);
}
}
tableArray.push(tableArray[i]);
}
return tableArray;
}
I am having problem solving this problem: the input is a set of 10 arrays where each array contains 5 different number in range of 1 - 20.
input =[ [14, 9, 1, 6, 16], [4, 15, 16, 14, 11], [16, 10, 2, 3, 8], [3, 17, 16, 6, 14], [19, 18, 14, 6, 20], [6, 15, 8, 7, 2], [15, 14, 2, 19, 3], [8, 2, 14, 10, 5], [11, 6, 8, 10, 18], [14, 10, 12, 4, 18] ]
I would like to generate a 10x20 matrix as output where each row has has 20 numbers with the following pattern:
output = [ [ 1, 0, 0, 0, 0, 6, 0, 0, 9, 0, 0, 0, 0, 14, 0, 16, 0, 0, 0, 0], [ 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 11, 0, 0, 14, 15, 16, 0, 0, 0, 0], [... ], ... ]
Im using JavaScript to solve this...
Create a new output array:
var out = [];
Loop over the input array. For each nested array create a new array in the output array padded with 20 zeros, and then just replace those elements in the output array with the value of the element in the nest input array in the right position. Since you know the size of the nested array, and it's small, its easier just to list each element rather than use an inner loop.
for (var i = 0, l = arr.length; i < l; i++) {
var el = arr[i];
out[i] = Uint8Array(20);
out[i][el[0] - 1] = el[0];
out[i][el[1] - 1] = el[1];
out[i][el[2] - 1] = el[2];
out[i][el[3] - 1] = el[3];
out[i][el[4] - 1] = el[4];
}
DEMO
If your browser doesn't support Uint8Array you can use a separate function to create a padded array:
function padArray() {
var out = [];
for (var i = 0, l = 20; i < l; i++) {
out.push(0);
}
return out;
}
And use:
out[i] = padArray();
You really should have tried it yourself. It's rather easy. Start with an array of 20 zeros, then fill the slots with the values from the array:
function posArray(arr, max) {
var res = [];
for (var i = 0; i < max; i++) res.push(0);
for (var i = 0; i < arr.length; i++) {
var a = arr[i];
if (a > 0 && a <= max) res[a - 1] = a;
}
return res;
}
var output = [];
for (var i = 0; i < input.length; i++) {
output.push(posArray(input[i], 20));
}
Something like this would also work (not tested):
var set1 = [14, 9, 1, 6, 16],
set2 = [4, 15, 16, 14, 11],
set3 = [16, 10, 2, 3, 8],
set4 = [3, 17, 16, 6, 14],
set5 = [19, 18, 14, 6, 20],
set6 = [6, 15, 8, 7, 2],
set7 = [15, 14, 2, 19, 3],
set8 = [8, 2, 14, 10, 5],
set9 = [11, 6, 8, 10, 18],
set10 = [14, 10, 12, 4, 18],
input = [set1, set2, set3, set4, set5, set6, set7, set8, set9, set10];
var output = [];
for (var e=0; e<input.length; e++) {
newRow = [];
for (var i=0;i<20; i++) {
if (input[e].indexOf(i) > -1) {
newRow.push(i);
}
else {
newRow.push(0);
}
}
output.push(newRow);
}
alert(output);