Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การกลับลำดับอาร์เรย์โดยคงตำแหน่งอักขระพิเศษ (#) ไว้ใน JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของค่าต่างๆ และกลับลำดับอาร์เรย์ แต่คงตำแหน่งของอักขระ '#' ไว้เดิม โดยเฉพาะตัวเลขจะถูกกลับลำดับ ขณะที่ '#' อยู่ที่ดัชนีเดิม

ตัวอย่าง: อาร์เรย์ [18, -4, '#', 0, 8, '#', 5] ควรคืนค่า:

[5, 8, "#", 0, -4, "#", 18]

ตัวอย่างโค้ด

const arr = [18, -4, '#', 0, 8, '#', 5];
const arr1 = [18, -4, 0, '#', 8, '#', 5];

const specialReverse = (arr = []) => {
  let removed = arr.reduce((acc, val, ind) => {
    return val === '#' ? acc.concat(ind) : acc;
  }, []);
  let reversed = arr.filter(val => val !== '#').reverse();
  removed.forEach(el => reversed.splice(el, 0, '#'));
  return reversed;
};

console.log(specialReverse(arr));
console.log(specialReverse(arr1));

ผลลัพธ์

ค่าที่แสดงในคอนโซลจะเป็นดังนี้:

[ 5, 8, '#', 0, -4, '#', 18 ] [ 5, 8, 0, '#', -4, '#', 18 ]