Reputation: 5768
I have 2 arrays, one of which is filled with elements and the other has empty elements, eg:
let arr1 = ['apples', 'bananas', 'oranges', 'strawberries', 'blueberries', 'pineapple']
let arr2 = [1,,3,,,4]
How do I remove both bananas, strawberries and blueberries and the empty element in arr2
, should look something like this:
let arr1 = ['apples', 'oranges', 'pineapple']
let arr2 = [1,3,4]
edit: added more elements to the array for scale.
Upvotes: 1
Views: 66
Reputation: 360
you can iterate and return only the expected value something like the below snippet
After edit please follow the below snippet
let arr1 = ['apples', 'bananas', 'oranges']
let arr2 = [1, , 3]
var filtered = arr2.filter((item, index) => {
if (arr2[index] != null) {
arr1.splice(index, index);
return true;
} else {
return false
}
});
console.log(filtered);
console.log(arr1);
Upvotes: 1
Reputation: 22370
You can use Array.prototype.filter()
:
let arr1 = ['apples', 'bananas', 'oranges', 'strawberries', 'blueberries', 'pineapple'];
let arr2 = [1,,3,,,4];
arr1 = arr1.filter((x, i) => arr2[i] !== undefined);
arr2 = arr2.filter(x => x !== undefined);
console.log(arr1);
console.log(arr2);
Upvotes: 2
Reputation: 941
You can use filter()
let arr1 = ['apples', 'bananas', 'oranges', 'strawberries', 'blueberries', 'pineapple']
let arr2 = [1,,3,,,4]
let result = arr1.filter((item, index) => {
return arr2[index] !== undefined;
});
console.log(result); // Outputs: ["apples", "oranges", "pineapple"]
Check this fiddle.
Upvotes: 1
Reputation:
const filterOutItems = (array, itemValue = undefined) {
if (typeof itemValue == undefined) {
return array.filter((el) => !!el);
} else {
return array.filter((el) => el != itemValue);
}
}
The filter method will return only the items that satisfy the predicate.
Upvotes: 0
Reputation: 386620
You could map and filter with true
because filter omits sparse items.
let array1 = ['apples', 'bananas', 'oranges'],
array2 = [1, , 3],
result1 = array2.map((_, i) => array1[i]).filter(_ => true),
result2 = array2.filter(_ => true);
console.log(result1);
console.log(result2);
Upvotes: 2