0

I have to use a.splice(index, 0, value) to solve.

this is what I have so far, but the value for final is an empty array(i initialized to null for debugging purposes); I think the problem is with my splice, because my output is just an empty array but i'm pretty sure my syntax is correct.

Input

a == [7, 10, 15, 54]

x = 99

Output:

[7, 10, 99, 15, 54]


function solution(a, x) {
 
 let count = a.length+1
 let mid = count/2
 let final = null
 if (mid % 2 === 0) {
         final = a.splice(a[mid], 0, x)
    } else {
        let middle = mid - 1
         final = a.splice(a[middle], 0, x)
    }
    
    return final
}

Edit:

I see the comment and have amended the code to this:

 let count = a.length+1
 let mid = count/2
 if (mid % 2 === 0) {
        a.splice(mid, 0, x)
    } else if (mid % 2 == 1) {
        let middle = mid-1
        a.splice(middle, 0, x)
    }
    return a
}

but this input fails because it doesn't want to insert the new value?

**Input:

a: [64, 38, 22, 27, 62, 41] x: 90

Output:

[64, 38, 22, 27, 62, 41]

Expected Output:

[64, 38, 22, 90, 27, 62, 41]**

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#return_value – Phil Oct 13 '22 at 02:28
  • As Phil commented, if you read the doc,you can find that **If no elements are removed, an empty array is returned.** – flyingfox Oct 13 '22 at 02:29

2 Answers2

0

Reading offical document of splice(),we can find below description:

Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

Since you are not delete element,that's the reason,so you need to return the element directly

function solution(a, x) {
 
 let count = a.length+1
 let mid = count/2
 if (mid % 2 === 0) {
   a.splice(mid, 0, x)
  } else {
   let middle = mid - 1
   a.splice(middle, 0, x)
  }
    
  return a
}

let data = [7, 10, 15, 54,55]
let x = 99
console.log(solution(data,x))
flyingfox
  • 13,414
  • 3
  • 24
  • 39
0

First splice modify the original array. So you will have to return the original array and there is no need of final variable here. Secondly you have to use Math.floor or Math.ceil as mid - 1 will still be a floating point number and lastly a[middle] in a.splice(a[middle]...) need to be replaced only with middle

function solution(a, x) {

  let count = a.length + 1
  let mid = count / 2
  let final = null
  if (mid % 2 === 0) {
    a.splice(a[mid], 0, x)
  } else {
    let middle = Math.ceil(mid - 1);
    a.splice(middle, 0, x)
  }
  return a;
}


console.log(solution([7, 10, 15, 54], 99))
brk
  • 48,835
  • 10
  • 56
  • 78