如何将数组中的指定元素移至末尾且保留其余元素原有顺序
数组指定元素统一后置实现方案
需求说明
将随机顺序数组中的指定元素从原位置移除,按固定顺序放到数组末尾,其余非指定元素保留原有相对顺序,同时过滤数组中的空值。
实现思路
- 第一步:过滤原数组,仅保留不属于后置指定集合、且非空的元素,天然保留原有相对顺序
- 第二步:将固定顺序的指定后置元素拼接在过滤后的数组末尾
代码实现
// 封装处理函数,参数为原数组、固定后置元素集合 function processArray(originArr, lastElementList) { // 过滤正常元素:排除后置元素 + 排除空值 const normalElements = originArr.filter(item => { return !lastElementList.includes(item) && item.trim() !== '' }) // 拼接固定顺序的后置元素 return normalElements.concat(lastElementList) } // 测试用例 const input_always_place_at_last = ["me","you"] const download_array1 = ["me","father","mother","sister","you","brother","grandfather","grandmother"] const download_array2 = ["brother","grandfather","me","grandmother","father","mother","sister","you"] const download_array3 = ["you","father","mother","grandmother","sister","me","brother","grandfather",""] // 调用输出 console.log(processArray(download_array1, input_always_place_at_last)) console.log(processArray(download_array2, input_always_place_at_last)) console.log(processArray(download_array3, input_always_place_at_last))
输出结果
和需求预期完全一致:
["father","mother","sister","brother","grandfather","grandmother","me","you"] ["brother","grandfather","grandmother","father","mother","sister","me","you"] ["father","mother","grandmother","sister","brother","grandfather","me","you"]
原有代码错误说明
你尝试的download_array1.includes(input_always_place_at_last).push(input_always_place_at_last)存在两个核心问题:
Array.includes()方法仅支持传入单个元素判断是否存在,直接传入数组input_always_place_at_last只会判断原数组中是否存在该数组作为子元素,永远返回布尔值false,布尔值不存在push方法,运行会直接抛出类型错误。- 逻辑缺失:没有先移除原数组中已存在的
me、you元素,直接推送会导致这两个元素在数组中重复出现。
内容的提问来源于stack exchange,提问作者user16731842
相关产品推荐
相关产品推荐

