简体   繁体   中英

Remove empty elements in 2 different arrays in javascript

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.

You can use Array.prototype. :

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

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

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM