How to remove multiple sequential items of an array - JavaScript - javascript

I am curious to know how I can quickly and most efficiently remove a number of items from an array in JavaScript without creating a loop.
EXAMPLE:
var array = [1,2,3,4,5,6,7,8,9];
array.remove[0..4]; //pseudo code
console.log(array);//result would then be [6,7,8,9]
Is there a function for this, or is a custom loop required? Rudimentary question I suppose, but just wondering out of curiosity.

Use Array#splice:
var array = [1,2,3,4,5,6,7,8,9];
array.splice(0, 4); // returns [1,2,3,4]
console.log(array); // logs [5,6,7,8,9]

You could just use .slice() on the array.
var array = [1,2,3,4,5,6,7,8,9];
array = array.slice(5,array.length);

Using filter method
var a = [1,2,3,4,5,6,7,8,9], b = [];
b = a.filter(function(element, index){ return index > 4 });
Output of b[]
[6,7,8,9]

Related

Duplicating array in nested array with one value change, changes entire nested array in javascript

I have an nested array. Example
let array = [['a','e1'],['b','b1']]
What i want to achive is a new nested array with a copy of one of the array's and a change to that copy.
when i run it though a loop (tried for and foreach) it duplicates the change throughout the entire nested array.
here is an example of the code (note its not key: index and just an example. the actual inside array contains 11 values in total)
let array = [['a','e1'],['b','b1']]
let result = []
for(let x of array){
result.push(x);
if(x[1]==='e1'){
let newRow = x;
newRow[1] = 'e2'
result.push(newRow);
}
}
//result: [[a,e2],[a,e2],[b,b1]]
let needResult = [['a','e1'],['a','e2'],['b','b1']]
Any assistance in this would be greatly appreciated.
Working example of the script : https://stackblitz.com/edit/js-ah1bvf?file=index.js
Thanks
Instead of use let newRow = x;, as #tadman said in the comment you need to use another way like create a new array let newRow = []; //for example
let array = [['a','e1'],['b','b1'], ['c', 'e1']]
let result = []
for(let x of array){
result.push(x);
if(x[1]==='e1'){
const newRow = [];
newRow[0] = x[0];
newRow[1] = 'e2'
result.push(newRow);
}
}
console.log(result)
As #tadman said in the comment :
let newRow = [...x] // works.
I did not select #simons answer though valid as stated in my question the array can be quite large and I don't necessarily know exactly how long it is.
Thanks for the help!

Giving an array of indexes, how to push items from one array to another depending on the indexes that are specified?

I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
Another array with the order it should be in :
var myOrder = [0,2,1];
My resulting array would look like this :
var finalArray = [['Apples',22],['Berry',23],['Orange',55]]
My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!
This is a simple map() that doesn't require anything else
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let final = myOrder.map(i => myArray[i])
console.log(final)
The optimal way appears to me to be:
Initialize empty finalArray
Loop over your myOrder array
2.1. Push myArray[index] to finalArray
Like so:
let finalArray = [];
for(let index of myOrder) {
finalArray.push(myArray[index]);
}
Review the for...of syntax if you're not familiar with it.
You can use splice to insert so long as the same number of elements are present in both the arrays.
You iterate over the myOrder array and then use splice, to which the index of the new array is the current value of the iteration and then use array present in the index position of myArray
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray = [];
myOrder.forEach(function(val, index) {
finalArray.splice(val, 0, myArray[index]);
});
console.log(finalArray);
Easy enough using .reduce:
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
function reorder(array, order) {
return order.reduce((newArray, orderIndex) => {
newArray.push(array[orderIndex]);
return newArray;
}, []);
}
console.log(reorder(myArray, myOrder))
function reorder(arr, order) {
return order.map(function(i) {
return arr[i];
});
}
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
reorder(myArray, myOrder); // => [["Apples",22],["Berry",23],["Orange",55]]
One of way solving this will be
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray;
for (x in myOrder) {
finalArray[x] = myArray[myOrder[x]];
}
This is a beginning level solution. Also you use libraries available for java script such as underscore.js(http://underscorejs.org/) for such operations on Array and Object.
Also you can use ECMA 6, for doing this which will reduce your line of coding.
Example-
var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let finalArray = myOrder.map(i => myArray[i])
This is the new way of coding in javascript.
In my point of view, it will be easy if you learn latest version of Java script(ECMAscript 6)

Delete first element from each array in javascript

I have a multi dimensional array like this.
var myArray = [['aaa','1','2.33','44'],['bbb','1','2.33','44'],['ccc','1','2.33','44']]
I want to remove all the first element to get a result like this.
var myArray = [['1','2.33','44'],['1','2.33','44'],['1','2.33','44']]
Please Help me. Thanks
Use .forEach to loop over the nested arrays and then .splice them. Splice will remove the first item in the nested array and effect the current array.
var myArray = [['aaa','1','2.33','44'],['bbb','1','2.33','44'],['ccc','1','2.33','44']];
myArray.forEach(array => array.splice(0,1));
console.log(myArray);
Base on the comment you can also use .shift() function to remove the first item.
var myArray = [['aaa','1','2.33','44'],['bbb','1','2.33','44'],['ccc','1','2.33','44']];
myArray.forEach(array => array.shift());
console.log(myArray);
You can try this
var myArray = [['aaa','1','2.33','44'],['bbb','1','2.33','44'],['ccc','1','2.33','44']];
var done = function(){
console.log(myArray);
};
myArray.forEach(function(array){
array.splice(0,1);
done();
});
Output
[['1','2.33','44'],['1','2.33','44'],['1','2.33','44']];

Immutable - change elements in array with slice (no splice)

How is possible to change 3/4 elements? Expected output is [1,2,4,3,5]
let list = [1,2,3,4,5];
const removeElement = list.indexOf(3); // remove number 3
list.slice(0, removeElement).concat(list.slice(removeElement+1)) // [1,2,4,5]
...next push number 3 after number 4 without splice
slice doesn't mutate the array on which it operates so you need to assign a value to what it returns
let list = [1,2,3,4,5];
const removeElement = list.indexOf(3); // remove number 3
var newList = list.slice(0, removeElement).concat(list.slice(removeElement+1)) // [1,2,4,5]
If you are prepared to use ES2015 syntax, you can use the spread operator as follows:
const removeElement = list.indexOf(3); // remove number 3
var es6List = [
...list.slice(0, removeElement),
...list.slice(removeElement+1)
];
console.log(es6List);
fiddle
The simplest way to write this is to use the spread operator:
let newList = [...list.slice(0, 2), list[3], list[2], ...list.slice(4)];
var list = [1,2,3,4,5];
var numToRemove = 3;
var removeElementIndex = list.indexOf(numToRemove);
var afterRemoveElement = list[removeElementIndex+1];
list.slice(0, removeElementIndex).concat(afterRemoveElement).concat(numToRemove).concat(list.slice(removeElementIndex+2)) // [1,2,4,3,5]
Object.assign actually works here
const newList = Object.assign([], list, {
2: list[3],
3: list[2],
});
list // [1,2,3,4,5]
newList // [1,2,4,3,5]
newList === list // false
The easer solution might be using filter instead of splice or slice. According to documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
It means the original array stays immutable. The only difference is that in this case, you have to know the value you want to delete instead of index.
let list = [1,2,3,4,5];
list.filter((item) => item !== 3);
Arrays are objects, use Object.assign() and access elements with property name expressions.
var numToMove = 2;
console.log(Object.assign(list, {[numToMove]: list[numToMove+1]},
{[numToMove+1]: list[numToMove]}));
// [1, 2, 4, 3, 5]

How to use push with sub-arrays?

I have 3 arrays like:
var arr1 = [];
var arr2 = [];
var arr3 = [];
//When I want to add something into array then I use
arr1.push("text");
arr2.push("text");
but is it possible to make something like the following example?
//example:
var arr = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
//and then iterate like:
for(item in arr['group1'])
console.log(item);
is it even possible to do something like that? I have tried but does not work.
There's a fundamental misunderstanding though, arr is an array but you're using it as an associative array, which in JavaScript is better represented with an object {}. for...in is for objects, NOT arrays, the MDN has a warning note about it:
for..in should not be used to iterate over an Array where index order
is important...
I would advice even if index is trivial to use a regular for loop or a forEach.
Consider using the following, more appropiate approach.
var obj = {
group1: ['text1'],
group2: ['text2'],
group3: ['text3']
};
// pushing more strings
obj.group1.push('foo');
obj['group2'].push('baz');
You're treating arr['group1'] as an array (by using .push()), but you haven't declared it as an array.
var arr = [];
arr['group1'] = [];
arr['group2'] = [];
arr['group3'] = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
It seems you're actually looking for Javascript Objects instead of arrays.
Also, you need to create these objects first.
var obj = {group1:[],group2:[],group3:[]};
/* or
var obj = {};
obj.group1 = [];
*/
obj['group1'].push("text1");
// or obj.group1.push("text1");
The for...in structure sets your for variable to the key, not the value. Assuming arr['group1'] is an array, this will work fine:
//example:
var arr = [];
arr['group1'].push("text1");
arr['group2'].push("text2");
arr['group2'].push("textn");
//and then iterate like:
for(item in arr['group1'])
console.log(arr['group1'][item]);​

Categories