繁体   English   中英

在每个 nt-h 数组元素后插入新元素

[英]Insert new element after each nt-h array elements

我有一个名为a的数组,我想在数组a每个nt-h元素之后插入一个元素。 例如,我想将字符串XXX放在数组a3元素之后,结果得到一个新数组b ,如下例所示:

 let a = [undefined, "", 0, [], "ee", false, null, {}, Date(), true, (z)=>2*z, Array(0), NaN ]; let b = [undefined, "", 0, "XXX", [], "ee", false, "XXX", null, {}, Date(), "XXX", true, (z)=>2*z, [], "XXX", NaN]; console.log(a, b);

我试过这样做:

b = [];
a.map((x, i) => b.push((i + 1) % 3 ? x : "XXX"));

https://jsfiddle.net/Lamik/vjfaqn3u/16/

但是,存在一个问题:输出数组b的长度与输入数组a的长度相同,这是错误的 任何想法或替代解决方案?

(更新:就地解决方案也可以;我剪切了数组a

这是一种使用while循环和Array.splice()方法的解决方案,每N个元素插入一个token 此外,逻辑被包装在一个函数中。

 let insertTokenEveryN = (arr, token, n) => { // Clone the received array, so we don't mutate the // original one. You can ignore this if you don't mind. let a = arr.slice(0); // Insert the <token> every <n> elements. let idx = n; while (idx <= a.length) { a.splice(idx, 0, token); idx += n + 1; } return a; }; let array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; let res1 = insertTokenEveryN(array, "XXX", 2); let res2 = insertTokenEveryN(array, "XXX", 3); let res3 = insertTokenEveryN(array, "*", 4); console.log(JSON.stringify(res1)); console.log(JSON.stringify(res2)); console.log(JSON.stringify(res3));
 .as-console {background-color:black;important: color;lime.}:as-console-wrapper {max-height;100%:important; top:0;}

reduce()或只是一个for循环可能是更好的情况。 map()将始终为您提供一个相同大小的新数组。 如果你对结束和开始都很小心,你应该能够在一般情况下使用类似的东西让它工作。

 let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] function insert_after(arr, str, n){ return arr.reduce((arr, item, i) =>{ arr.push(item) if (i % n == n-1) arr.push(str) return arr }, []) } console.log(insert_after(arr, 'x', 2).join(',')) console.log(insert_after(arr, 'x', 3).join(','))

在您的示例中,您改为推而不是在元素之后。 如果你想使用map你可以使用apply来推送一个或两个元素

 a = [1,2,3,4,5,6,7,8,9,10] b = [] a.map((x,i)=> Array.prototype.push.apply(b, (i+1)%3? [x]: [x, "XXX"])) console.log(b.join(', '))

 let a= [undefined, "", 0, [], "ee", false, null, {}, Date(), true, (z)=>2*z, Array(0), NaN ]; let n = 3+1; let currentPosition = 3; let temp ='xxxxxx'; console.log('Before assignment:::',a.length, a); while(currentPosition <= (a.length+1)){ a.splice(currentPosition,0,temp); currentPosition += n; } console.log('new array length:::::',a.length,a);

我希望这个解决方案适合您。 在插入元素之前,长度为 13。在 17 之后。

根据给定的示例数组ab ,您可以尝试使用以下代码来获得预期的输出。

let a= [undefined, "", 0, Array(0), "eeeeeeeeee", null, "cccccccc", "bbbbbbb", "ddddddddd", Array(0), "bbbbbbb", {}, undefined, "bbbbbbb", {}, null, 0, "ddddddddd", null, "eeeeeeeeee", "ddddddddd", "bbbbbbb", undefined, "cccccccc", "ddddddddd", "ddddddddd", undefined, undefined, "eeeeeeeeee", {}, "", "", undefined, "", "eeeeeeeeee", undefined, Array(0), Array(0), 0, "ddddddddd", "", "", null, null, "bbbbbbb", "", Array(0), null, "ddddddddd", {}];
    let b = [];
    let j = 0, insertIndex = 15;
    let insertVal = "INSERT_VAL";
    for(let i=0; i< a.length;){
        b[j++] = a[i++];
        if(i%insertIndex ==0){
            b[j++] = insertVal;
        }
    }
    console.log(b);

受答案Hamlet HakobyanMark Meyer的启发,我使用 map 和 reduce(时间复杂度O(n) )为不可变解决方案提供了 oneliners

let b=[]; a.forEach((x,i)=>b.push(x,...(i+1)%k ? [] : ["XXX"]));  

let c = a.reduce((t,x,i)=>t.push(x,...(i+1)%k ? [] : ["XXX"])&&t, []);

和就地解决方案( a复杂度O(n/k)

for(let i=a.length/k|0; i; i--) a.splice(i*k,0,"XXX");

我阅读了您所有的答案并给出了 +1,因为它们很有趣,很难选择最好的,但最终我选择了 Amaranadh Meda 答案,因为他首先表明我们可以将时间复杂度从O(n)降低到O(n/k)其中 n 是数组a的大小, k是新插入元素之间的间隙大小。

 let a= [undefined, "", 0, [], "ee", false, null, {}, Date(), true, (z)=>2*z, Array(0), NaN ]; let k=3; // gap // immutable -> result in b let b=[]; a.forEach((x,i)=>b.push(x,...(i+1)%k? []: ["XXX"])); let c = a.reduce((t,x,i)=>t.push(x,...(i+1)%k?[]: ["XXX"])&&t, []); // in-place -> result in a for(let i=a.length/k|0; i; i--) a.splice(i*k,0,"XXX"); console.log('b=',b); console.log('c=',c); console.log('a=',a);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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