JS For loop and Splice problem, use map(), new set(), filter()

 

1. Modifying an array while iterating over it can lead to skipped elements or unexpected behavior.
2. The resolve function should be called in all execution paths of the promise.
1. 在迭代数组时对其进行修改可能会导致 跳过元素或出现意外行为, 数据不准.
2. 应在 Promise 的所有执行路径中调用 resolve 函数
// Remove  the common sku from WH01 and DC01 return sku
	async function removeCommonList(omsWh01StockList, returnStockList){
		return new Promise((resolve, reject) => {
		   try {
			  if (omsWh01StockList && omsWh01StockList.length > 0){	
				  // Remove  the common sku from WH01 and DC01 return sku

					/**
					 * @description:   1. Modifying an array while iterating over it can lead to skipped elements or unexpected behavior.
										 2. The resolve function should be called in all execution paths of the promise.
					* @author: Grant
					* @date: 
					*/
				 
				  for (let i = 0; i < omsWh01StockList.length; i++) {
					  let el = omsWh01StockList[i];
					  returnStockList.forEach(rl => {
						  if(rl.return_sku === el.sku){
							  console.log("Inner of DC01 return sku and Wh01 sku : ", el.sku);
							  omsWh01StockList.splice(i, 1)
						  }
					  })
					  
				  }
				  resolve(omsWh01StockList)
			  }
			  
		   } catch (error) {
			  console.log(error);
			  
		   }
		}) 
  
	 }

 Optimized code: 


	async function filterOMSWhPriority(omsWhPriorityList, omsWh01StockList){
        return new Promise((resolve, reject) => {
			try {
				let filteredList = [];
				console.log('Before Splice arr length : ', omsWhPriorityList.length);
				// Remove omsWh01StockList in  omsWhPriorityList
				if(omsWhPriorityList && omsWh01StockList && omsWh01StockList.length > 0 ){
					
				    // Create a Set of return SKUs for faster lookup
					// let wh01Skus = omsWh01StockList.map(ol => ol.sku);
					let wh01Skus = new Set(omsWh01StockList.map(ol => ol.sku));

                    // Filter out the common SKUs
					filteredList = omsWhPriorityList.filter(el => !wh01Skus.has(el.SKU));
					resolve(filteredList);
				} else {
					resolve(omsWhPriorityList);	

				}
				console.log('After Splice arr length : ', filteredList.length > 0 ? filteredList.length : omsWhPriorityList.length);			

			} catch (error) {
				console.log(error);
			}
		})

	}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值