简体   繁体   中英

How to overwrite a array with a second array, only if the specific index is a valid number?

I have 2 arrays:

var array1 = [1,4,8,10,12]
var array2 = [3,2,undefined,9,undefined]

So, I need to have an result array where all values of array1 have been replaced by the values of array2 , but only in case the specific index of array2 is a not undefined (a valid number). The value of the index of array1 should persist in that case.

The result should be:

resultArray = [3, 2, 8, 9, 12]

I couldn't get it work.

 const resultArray = array2.map((el, i) => isNaN(el) ? array1[i] : el);

注意,由于一些非常有趣的语言设计,它将代替undefined但不会为null

You could check explicit for undefined and take the value of array1 for mapping.

 var array1 = [1, 4, 8, 10, 12], array2 = [3, 2, undefined, 9, undefined], result = array2.map((v, i) => v === undefined ? array1[i] : v); console.log(result) 

An alternative using the function Array.from

 var array1 = [1, 4, 8, 10, 12], array2 = [3, 2, undefined, 9, undefined], result = Array.from(array2, (n, i) => isNaN(n) ? array1[i] : n); console.log(result); 
 <script src="https://codepen.io/egomezr/pen/dmLLwP.js"></script> 

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