Remove element from array (splice) - javascript

Basic question on .splice() method, and how best to remove an element from an array.
I want to remove an item from an array with .splice() but when I do, I want to have the original array minus the removed element returned. .splice() returns the removed element instead.
var arr = [1, 2, 3, 4, 5, 6, 7]
var newArr = arr.splice(3, 1)
console.log(newArr) // [4]
// whereas I want [1, 2, 3, 5, 6, 7]
What's the best, and most eloquent way to do this?

Using the spread operator, you can do:
var arr = [1,2,3,4,5,6],
indexToRemove = 3,
newArr = [
...arr.slice(0,indexToRemove),
...arr.slice(indexToRemove+1)
]
Or if you want to use ES5, it can look something like:
var arr = [1,2,3,4,5,6],
indexToRemove = 3,
newArr = [].concat(arr.slice(0,indexToRemove)).concat(arr.slice(indexToRemove+1))

.splice mutates the array in place and returns the removed elements. So unless you actually need a function that returns the array itself, just access arr:
var arr = [1, 2, 3, 4, 5, 6, 7]
arr.splice(3, 1)
console.log(arr) // [1, 2, 3, 5, 6, 7]
You can create a wrapper function that performs the splice and returns the array:
function remove(arr, index) {
arr.splice(index, 1)
return arr;
}
var newArr = remove(arr, 3);
// Note: `newArr` is not a new array, it has the same value as `arr`
If you want to create a new array, without mutating the original array, you could use .filter:
var newArr = arr.filter(function(element, index) {
return index !== 3;
}); // [1, 2, 3, 5, 6, 7]
arr; // [1, 2, 3, 4, 5, 6, 7]

Related

Javascript splice last element

var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr = arr.splice(4, 1)
console.log(arr)
//[5]
I want to remove only the last element. Why does it remove every element except the last one?
You need to omit the assignment.
var arr = [1, 2, 3, 4, 5]
console.log(...arr); // [1, 2, 3, 4, 5]
arr.splice(4, 1);
console.log(...arr); // [1, 2, 3, 4]
If you like just to delete the last one, you could take a negative index with Array#splice. This works for any other index from the end.
var arr = [1, 2, 3, 4, 5]
console.log(...arr); // [1, 2, 3, 4, 5]
arr.splice(-1, 1);
console.log(...arr); // [1, 2, 3, 4]
Array#splice modifies the array in place and returns the removed portion. You should not reassign the removed portion to the variable.
var arr = [1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr);
splice alters the array and returns the removed item(s) in a new array.
By the way, you should use pop which is better suited for this like so:
var arr = [1, 2, 3, 4, 5];
arr.pop();
console.log(arr);
pop removes the last item of the array.
This is a more general approach:
var arr = [1, 2, 3, 4, 5]
arr.splice(arr.length - 1);
console.log(arr)
You can access to the last arr element by splice(-1), then you stored that value (5) into a variable (newArr). The original array now values [1, 2, 3, 4].
let arr = [1, 2, 3, 4, 5];
let newArr = arr.splice(-1);
console.log(arr) //[1, 2, 3, 4]
console.log(newArr) //[5]
The splice method takes two parameters: a beginning index (inclusive) and an ending index (exclusive). The below will do what you described.
arr = arr.splice(0, 4)
In your code, you are reassigning the arr to the spliced value, which is [5]. the way you should do it is,
var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr)
//[1, 2, 3, 4]
This should give you the result you are looking for;
The splice() method adds/removes items to/from an array, and returns the removed items in the form of an array.
Syntax :
let arrDeletedItems = array.splice(starting_index , index to which you want to add or remove an item , item 1 , item 2 , item 3 ...so on )
let arr = [1, 2, 3, 4, 5]
arr.splice(4, 1)
so in your case, you are starting from index 4 which means the value "5" and you are removing the 1st element that starts from index 4 which is the value '5'. So the splice method would return a new array (as it returns a new array of the removed elements) containing only 5.
To get back an array containing all the elements except the last element 5 you should write :
arr = arr.splice(0,4)
which means that start from index 0 and remove elements till index 4.
Splice method returns the removed item(s) in an array so what is happening is you are assigning the returned to the original array. Instead do this
var arr = [1, 2, 3, 4, 5];
console.log(arr);
//[1, 2, 3, 4, 5]
arr.splice(4, 1);
console.log(arr);
Splice modifies array in place and returns removed part as a new array.
To get expected result you want to use expression:
var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr)
//[5]
You can also remove the last element from the array with rest operator
const array = [1, 2, 3, 4, 5]
const [ ...newArray, last ] = array

Javascript: How to find difference for two number arrays

I need to create a new array made up of unique elements from two separate arrays.
I have converted both arrays into a single array and then converted this into an object to check the frequency of the elements. If the value of an object property is 1 (making it a unique property), I want to return it to an array (minus the value). Is there a straightforward way to achieve this?
Edits: Moved result outside for loop. Expected output should be [4]
function diffArray(arr1, arr2) {
var finalArr = [];
var countObj = {};
var newArr = [...arr1, ...arr2];
for (var i = 0; i < newArr.length; i++) {
if (!countObj[newArr[i]]) countObj[newArr[i]] = 0;
++countObj[newArr[i]];
}
for (var key in countObj) {
if (countObj[key] === 1) {
finalArr.push(key);
}
} return finalArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
If I understand correctly, you're wanting to find the difference between arr1 and arr2, and returns that difference (if any) as a new array of items (that are distinct in either array).
There are a number of ways this can be achieved. One approach is as follows:
function diffArray(arr1, arr2) {
const result = [];
const combination = [...arr1, ...arr2];
/* Obtain set of unique values from each array */
const set1 = new Set(arr1);
const set2 = new Set(arr2);
for(const item of combination) {
/* Iterate combined array, adding values to result that aren't
present in both arrays (ie exist in one or the other, "difference") */
if(!(set1.has(item) && set2.has(item))) {
result.push(item);
}
}
return result;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), " should be [4]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5]), " should be [8]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5, 9]), " should be [8, 9]");
console.log(diffArray([1, 2], [1, 2]), " should be []");

Remove minimum value from Array, but if duplicate remove only once

I have the following function which is supposed to remove the smallest value from an array, but if this is a duplicate it will just remove the first one and leave the others.
var array1 = [1, 2, 3, 4, 5];
var array2 = [5, 3, 2, 1, 4];
var array3 = [2, 2, 1, 2, 1];
function removeSmallest(numbers) {
return numbers.filter(function(elem, pos, self) {
if(elem == Math.min.apply(null, numbers) && pos == self.indexOf(elem)) {
// Remove element from Array
console.log(elem, pos);
numbers.splice(pos, 1);
};
return numbers;
});
};
Via console.log(elem, pos) I understand that I have correctly identified the smallest and first element in the array, but when I try to remove it through splice(), I end up getting the following result for the arrays:
array1 = [1, 3, 4, 5]; // But I expected [2, 3, 4, 5]
array2 = [5, 3, 2, 1]; // But I expected [5, 3, 2, 4]
array3 = [2, 2, 1, 1]; // But I expected [2, 2, 2, 1]
Do you know what is the issue with my code? Thanks in advance for your replies!
function removeSmallest(numbers) {
const smallest = Math.min.apply(null, numbers);
const pos = numbers.indexOf(smallest);
return numbers.slice(0, pos).concat(numbers.slice(pos + 1));
};
You shouldn't use filter() the way you do. It's also a good practice that a function should return a new array rather than modifying the existing one and you definitely shouldn't modify an array while iterating over it.
function removeSmallest(arr){
var temp=arr.slice(),smallElement=null;
temp.sort(sortReverse);
smallElement=temp[temp.length-1];
var position=arr.indexOf(smallElement);
arr.splice(pos,1);
console.log(arr);
}
function sortReverse (a,b){
if(a<b){return 1}
else if(a>b){return -1;}
else{return 0;}
}
var array1 = [1, 2, 3, 4, 5];
removeSmallest(array1);

Check if all items can be found in another array

I need to check if all items in an array can be found within another array. That is, I need to check if one array is a subset of another array.
Example:
var array = [1, 2, 5, 7];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
Comparing these two arrays above should return true as all items in array can be found in otherArray.
var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
Comparing these two arrays above should return false as one of the items in array cannot be found in otherArray.
I have tried to use the indexOf method inside a for loop without success.
I hope someone could help me. :)
Use Array.prototype.every:
The every() method tests whether all elements in the array pass the test implemented by the provided function.
var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
var isSubset = array.every(function(val) {
return otherArray.indexOf(val) >= 0;
})
document.body.innerHTML = "Is array a subset of otherArray? " + isSubset;

Remove multiple elements from array by value in JS

When I want to remove one element, it is easy. This is my function:
function removeValues(array, value) {
for(var i=0; i<array.length; i++) {
if(array[i] == value) {
array.splice(i, 1);
break;
}
}
return array;
}
But how do I remove multiple elements?
Here a simple version using ES7:
// removing values
let items = [1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => !valuesToRemove.includes(i))
For a simple version for ES6
// removing values
let items =[1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => (valuesToRemove.indexOf(i) === -1))
const items = [0, 1, 2, 3, 4];
[1, 4, 3].reverse().forEach((index) => {
items.splice(index, 1)
})
// [0, 2, 4]
I believe you will find the kind of functionality you are looking for in Javascript's built in array functions... particularily Array.map(); and Array.filter();
//Array Filter
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
//Array Map (Can also be used to filter)
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]
/////UPDATE REFLECTING REMOVAL OF VALUES USING ARRAY MAP
var a = [1,2,3,4,5,6];
a.map(function(v,i){
if(v%2==0){
a.pop(i);
}
});
console.log(a);
// as shown above all array functions can be used within the call back to filter the original array. Alternativelty another array could be populated within the function and then aassigned to the variable a effectivley reducing the array.

Categories