1

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.

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

how do i make it so it doesn't filter out 0
@LittleBall Updated to deal with 0s, your example didn't start from 0, I thought if you had more items they would be larger numbers.
1

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

3 Comments

how do I scale this for more elements in arr1? I don't wanna hardcode the word 'bananas'
if you dont want to give bananas, What is the strategy how would you like to remove the elements ? I mean on what basis. Please let me know I am not able to understand that part
edited the question for a better understanding
1

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.

Comments

0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.