javascript Delete from array between 2 indices - javascript

With an array of: [1, 2, 3, 4, 5, 6]
I would like to delete between 2 indices such as 2 and 4 to produce [1, 2, null, null, 5, 6]. What's the easiest way to do this?
Hopefully better than this:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
let i = 2;
const rangeEnd = 9;
while (i < rangeEnd) {
delete array[i];
i++;
}
console.log(array)

If you want to use some native API you can actually do this with splice(). Otherwise, you should iterate a for loop through your array and change the value in each iteration.
Here is an example of how it would be done:
const array = [1, 2, 3, 4, 5, 6]
array.splice(3, 2, null, null) // the First element is beginning index and the second is count one will indicate how many indexes you need to traverse from the first one, then you should provide replace element for each of them.
console.log(array)
Note: For more info about it you can read more here.
There is a possible workaround for large scale replacement, so I will give it a touch here:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var anotherArr = Array(2).fill(null); // or you can simply define [null, null, ...]
Array.prototype.splice.apply(arr, [3, anotherArr.length].concat(anotherArr));
console.log(arr);

As you mean the range (2, 4] so you can follow this:
The range is: lower limit exclusive and the upper limit inclusive.
const arr = [1, 2, 3, 4, 5, 6];
const deleteRange = (arr, f, t) => {
return arr.map((item, i) => {
if (i + 1 > f && i + 1 <= t) {
return null;
}
return item;
})
}
console.log(deleteRange(arr, 2, 4));

Related

Multiplying elements in arrays using the forEach function

I'm currently learning about arrays and the different ways to manipulate them. I was asked to: "multiply 5 to the given array using the forEach function"
Here is my code so far.
It looks as if everything works when I console.log in the forEach function, but when I log the console for the array it's read as undefined.
let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
function multiplyNumbers() {
let numbers;
multiplyArray.forEach(function(element) {
let fiveTimesNum;
fiveTimesNum = (element * 5);
element = fiveTimesNum;
console.log(element)
});
console.log('The array(element) value is read out correctly, but when I console log the array its value is ↓')
return numbers
}
multiplyArray = (multiplyNumbers());
console.log(multiplyArray);
From the task, it seems like you're supposed to update the given array. With a forEach loop you can reference the array you are looping on along with the index and value
let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
multiplyArray.forEach(function(val, i, arr){
arr[i] = val*5;
})
If you want to change the array multiplyArray in place you can it like this:
let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
multiplyArray.forEach(function(n,i,a){a[i]=5*n;});
console.log(multiplyArray);
Numbers was never defined correctly, please see example below.
You can use your mapped array to return the correct data.
let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];
function multiplyNumbers() {
multiplyArray.forEach(function(element) {
let fiveTimesNum;
fiveTimesNum = (element * 5);
element = fiveTimesNum;
console.log(element)
});
console.log('The array(element) value is read out correctly, but when I console log the array its value is ↓')
return multiplyArray
}
multiplyArray = (multiplyNumbers());
console.log(multiplyArray);

Get every second element of array with array methods

for learning purposes I want to get every second element of an array. I succeeded with a for loop:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function filterEverySecond(arr) {
let everySecondEl = [];
for (let i = 0; i < arr.length; i += 2) {
everySecondEl.push(arr[i]);
}
return everySecondEl;
}
console.log({
numbers,
result: filterEverySecond(numbers)
});
Now I want to achieve the same without a for loop, but by using array methods (forEach, filter, map or reduce). Can anyone recommend which method would be best here?
you can do it easily with filter
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filtered = numbers.filter((_, i) => i % 2 === 0)
console.log(filtered)
you just filter out the elements that have a odd index
You can use filter and check if the index of the current array element is divisible by 2:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log({
numbers,
result: numbers.filter((_, index) => index % 2 === 0)
});
You can use filter for index.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log({
numbers,
result: numbers.filter((n,i)=>i%2==0)
});
You could use a for each loop like so to get the same desired output:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = [];
numbers.forEach(number => {
if (number % 2 != 0) {
result.push(number);
}
});
console.log(numbers);
console.log(result);
The modulus operator returns the remainder of the two numbers when divided. For example: 1 % 2 will return 1 as the remainder. So in the if statement we are checking if the number is not divisible by 2.

method to check if a specific number with a group of numbers exists within an array in javascript

var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
need to check if 2, 3, 4 exist in the array. Only has to be 1 of these numbers to return true...not all. What's the best approach. I was thinking lodash includes, but I believe I can only pass in a single value.
Using Array#some and Array#includes:
const hasAny = (arr = [], nums = []) =>
nums.some(n => arr.includes(n));
console.log( hasAny([1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4]) );
If you want to get the intersection, you can filter the first array by the second array, or rather, whether or not the second array contains each element of the first. You can see which members were included, or check the size of the new array > 0 if you need a boolean (or use Mr Badawi's .some method).
var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
var needs = [2, 3, 4 ];
var check = numbers.filter(x=>needs.includes(x));
console.log(check);
var numbers = [3, 5, 6, 7, 8, 12, 20];
var needs = [2, 3, 4 ];
var check = numbers.filter(x=>needs.includes(x));
console.log(check);

Looping over the last few entries of an array

I'm trying to have a forEach loop over an array, but only the last few entries.
I'd know how to do this in a for loop, that'd look a bit like this:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
/* This will loop over the last 3 entries */
for(var x = arr.length; x >= 7; x--){
console.log(arr[x]);
}
Would there be any way of achieving the same results in a forEach loop?
You can use slice() and reverse() methods and then forEach() loop on that new array.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.slice(-3).reverse().forEach(e => console.log(e))
This is how you do it with forEach loop:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.forEach((element, index) => {
if(index>7) console.log(arr[index]);
})
You could take a classic approach by taking the count of the last elements and use it as counter and an offset for the index.
Then loop with while by decrementing and checking the counter.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
last = 3,
offset = array.length - last;
while (last--) {
console.log(array[last + offset]);
}

in javascript, how do you sort a subset of an array?

I have an array and would like to sort all but the last n elements.
For example, if the array is 10 elements long, would like elements 0 through 7 to be sorted while elements 8-9 are left in place.
var array = [5, 2, 6, 4, 1, 9, 3, 8, 7];
array = array.slice(0, 7).sort().concat(array.slice(7, 10));
// array is now [1, 2, 3, 4, 5, 6, 9, 8, 7]
If you need to sort the array in place (i.e. without creating a new, sorted array), which is what the sort() method does, you could do the following:
var array = [5, 2, 6, 4, 0, 1, 9, 3, 8, 7];
var unsorted = array.slice(7);
array.length = 7;
array.sort().push.apply(array, unsorted);
More generally, here's a function to sort a portion of an array in place. Like the sort() method, it also returns a reference to the array.
function partialSort(arr, start, end) {
var preSorted = arr.slice(0, start), postSorted = arr.slice(end);
var sorted = arr.slice(start, end).sort();
arr.length = 0;
arr.push.apply(arr, preSorted.concat(sorted).concat(postSorted));
return arr;
}
Example:
var array = [5, 2, 6, 4, 0, 1, 9, 3, 8, 7];
partialSort(array, 0, 7);
An ES6 riff on the solution provided by #darin
let subSort = (arr, i, n, sortFx) => [].concat(...arr.slice(0, i), ...arr.slice(i, i + n).sort(sortFx), ...arr.slice(i + n, arr.length));
i is the index where the subsection begins
n is the number of elements to sort
sortFx is the sorting function
So it's possible to sort a range within an array:
var array = [5, 2, 6, 4, 1, 9, 3, 8, 7];
// sort array beginning at index 2; sort 4 elements of array
subSort(array, 2, 4, (a, b) => a - b);
// array is now [5, 2, 1, 4, 6, 9, 3, 8, 7]
subSort(array, 2, 4, (a, b) => b - a);
// array is now [5, 2, 9, 6, 4, 1, 3, 8, 7]
subSort() can be used for objects of arbitrary complexity.
let arr = [2, 1, 5, 4, 3];
arr = [...arr.slice(0, 2), ...arr.slice(2).sort((a, b) => a - b)];
After sorting a sub-array the original array will be [2, 1, 3, 4, 5]

Categories

Resources