Javascript function remove from position in array - javascript

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);

Related

Control Flow and Iteration in Javascript

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]

Find the integers in an array which are bigger than all the elements to the right

I need to write a JS function which finds all the top integers, a top integer is an integer which is bigger than all the elements to its right. This is how far I've gotten:
jsBin
function testArray(array) {
var copy = [...array],
result = [],
number = [];
copy.forEach(function(el, i, ar) {
let sliced = array.slice(i);
console.log(sliced);
// number.push(sliced[0]);
number = [sliced[0]];
console.log(number);
for (let y = i; y <= sliced.length - 1; y++) {
// console.log(sliced,'sliced array')
console.log(sliced[y], 'for-loop currentValue')
// let newArray = sliced.filter(function(el,i,ar){
// return el < sliced[0];
// console.log(sliced[0]);
// console.log(el);
// console.log(ar);
// if (sliced[0] > el) {
// numbers.push(sliced[0]);
// }
// });
}
})
// console.log(newArray);
}
var arr1 = [1, 4, 3, 2]; //--> 4,3,2
var arr2 = [14, 24, 3, 19, 15, 17]; //--> 24,19,17
var arr3 = [41, 41, 34, 20]; //--> 41,34,24
var arr4 = [27, 19, 42, 2, 13, 45, 48]; //--> 48
You can do this with slice() and Math.max(). And if 17 is top integer in arr2. then 48 should be top too in arr4. My function returns array. You can print all of the array.
var arr1 = [1,4,3,2]; //--> 4,3,2
var arr2 = [14, 24, 3, 19, 15, 17]; //--> 24,19,17
var arr3 = [41, 41, 34, 20]; //--> 41,34,24
var arr4 = [27, 19, 42, 2, 13, 45, 48];
function topInts(arr){
const tops = [];
arr.forEach((item,i) => {
if(Math.max(...arr.slice(i)) === item) tops.push(item);
})
console.log([...new Set(tops)]);
}
topInts(arr1); // [4,3,2]
topInts(arr2); // [24,19,17]
topInts(arr3); // [41,34,24]
topInts(arr4); // [48]

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
}

Sum in nested loops returning incorrect

Not sure what is wrong here but I am trying to add a set of numbers in an array (not the whole array) but it looks like it is summing up the whole array:
function sumPrimes(num) {
var arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
var total = 0;
var index;
//loop through the whole array
for (var i = 0; i < arr.length; i++) {
//find matching prime number
if (num < arr[i]) {
// get index of prime number in the array
index = arr.indexOf(arr[i]);
//sum up total of prime numbers up to 'num'
for (var b = 0; b < index; b++) {
total = total + arr[index];
}
}
}
return total;
}
sumPrimes(10);
If your goal is to calculate the sum of all prime numbers less than the given number, then the solution is much easier.
Either
function sumPrimes(num) {
var arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
var total = 0;
for (var x of arr) {
if (x < num)
total += x;
else
break;
}
return total;
}
which works when arr is sorted, or
function sumPrimes(num) {
var arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
var total = 0;
arr.forEach(function(x) {
if (x < num)
total += x;
}, this);
return total;
}
that would work for an unsorted array as well.
You need to replace index with b:
//sum up total of prime numbers up to 'num'
for(var b=0; b<index; b++){
total = total + arr[b];
}
EDIT: and get rid of the outer loop

How to iterate only on part of 2D array in JavaScript?

I have 2D array
var arr = [[0, 1, 2, 3, 4, 5],
[6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]];
Now we are dividing this into smaller parts like 2x2. How to iterate only on part (block) of this array e.g: items with indexes arr[2][4], arr[2][5], arr[3][4], arr[3][5]?
Edit:
Seems question is not easy understandable. I want to iterate over blocks.
var blocks = 9;
var output = '';
for( var block = 0; block < blocks; block++) {
// actual iteration over array
for(var i = ... ) {
for(var j = ... ) {
output += arr[i][j] + ' ';
}
}
console.log(output);
output = '';
}
Expected output would be:
0 1 6 7
2 3 8 9
4 5 10 11
12 13 18 19
14 15 20 21
16 17 22 23
24 25 30 31
26 27 32 33
28 29 34 35
You need to nest for loops.
var arr = [[0, 1, 2, 3, 4, 5],
[6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]];
function loopThrough() {
for(int i = 0; i < arr.length; i++) {
// this will give you arr[0], arr[1], etc.
for(int j = 0; j < arr.length; j++) {
// this will give you arr[0][0], arr[0][1], etc.
console.log(arr[i][j]);
}
}
}
loopThrough();
If you want it to loop over only the last 2, then set j] = arr[i].length-2
<script type="text/javascript">
var arr = [[0, 1, 2, 3, 4, 5],
[6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]];
function loopThrough() {
for(var i = 0; i < arr.length; i++) {
// this will give you arr[0], arr[1], etc.
for(var j = arr[i].length-2; j < arr[i].length; j++) {
// this will give you arr[0][0], arr[0][1], etc.
console.log(arr[i][j]);
}
}
}
loopThrough();
</script>
function subblock_array(arr, startX, endX, startY, endY) {
var subArr = [];
for (var ii=startX; ii<endX; ii++) {
subArrY = [];
for (var jj=startY; jj<endY; jj++) {
subArrY.push(arr[ii][jj]);
}
subArr.push(subArrY);
}
return subArr;
}
subblock_array(arr, 2, 4, 4, 6)
You want to access those indexes in order :
arr[0][0] arr[0][1] arr[1][0] arr[1][1]
arr[0][2] arr[0][3] arr[1][2] arr[1][3]
[...]
arr[0][y-1] arr[0][y] arr[1][y-1] arr[1][y] // first two lines processed
arr[2][0] arr[2][1] arr[3][0] arr[3][1] // we continue with the next two lines
[...]
arr[2][y-1] arr[2][y] arr[3][y-1] arr[3][y]
[...]
arr[x-1][0] arr[x-1][1] arr[x][0] arr[x][1]
[...]
arr[x-1][y-1] arr[x-1][y] arr[x][y-1] arr[x][y]
As you can see we have two levels of iteration : a first one iterates over the lines, skipping every other one, and a second one iterates over the columns, skipping every other one.
The following code should implement this :
for (var x=0; x < arr.length; x+=2) {
for (var y=0; y < arr[x].length; y+=2) {
console.log(arr[x][y] + " " + arr[x][y+1] + " " + arr[x+1][y] + " " + arr[x+1][y+1]);
}
}
You will notice that we increment the iterations variables by two each loop, since the inner block consumes two columns and lines at once.
You would need a loop with an offset inner loop to iterate over the last two positions. Something like this would work, you can see the results on this js fiddle: https://jsfiddle.net/0wfysb38/3/
var arr = [[0, 1, 2, 3, 4, 5],
[6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]];
for(i = 0; i < arr.length - 1; i=i+2) {
for(j = 0; j < arr[i].length - 1; j=j+2) {
strOut = '';
strOut = strOut + ', ' +arr[i][j];
strOut = strOut + ', ' +arr[i][j+1];
strOut = strOut + ', ' +arr[i+1][j];
strOut = strOut + ', ' +arr[i+1][j+1];
strOut = strOut.substring(1,strOut.length)
console.log(strOut);
}
}
Edit: Updated to code to produce results matching the expected output. The key is to iterate the loops by 2, and seek the next position in the array by offsetting. This is not very flexible, and the array this loops over should be structured appropriately.

Categories

Resources