skip to Main Content

I want to start at index of "D" and go back up to index of "B" using the slice method

let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I","J"];

I’m expecting to get back

["D","C","B"]

3

Answers


  1. Slice cant to go back

    If you want to get ["D", "B","C"]

    let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I","J"]
    const letterD = letters.findIndex((l) => l === 'D'); //3
    const letterB = letters.findIndex((l) => l === 'B'); //1
    
    console.log([letters[letterD], ...letters.slice(letterB, letterD)]); //["D", "B", "C"]
    

    If you want to get ["B", "C", "D"]

    const letterD = letters.findIndex((l) => l === 'D'); //3
    const letterB = letters.findIndex((l) => l === 'B'); //1
     
    letters.slice(letterD-letterB-1, letterB+letterD)
    
    Login or Signup to reply.
  2. From what I understand, you want the first element in your final array to be "D", and then you want the elements in your slice to come after "D", starting with "B". The spread operator ... can be used to expand the slice into a new array that also contains "D".

    // Initialize the letters array
    const letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I","J"];
    
    // Get the index of B and D
    const bIndex = letters.indexOf("B");
    const dIndex = letters.indexOf("D");
    
    // Combine the slice with your desired character, D
    const finalSlice = [letters[dIndex], ...letters.slice(bIndex, dIndex)]
    console.log(finalSlice)
    Login or Signup to reply.
  3. Here is another attempt, using the Array methods .reverse() and .reduce():

    // Initialize the letters array
    const letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I","J"];
    
    // reverse-slice array arr from value v1 to v2:
    function reverseFromTo(arr,v1,v2){
      let go=false;
      return arr.reverse()
                .reduce((a,c)=>{
          if(!go && c==v1) go=true;
          if(go){
           a.push(c);
           if(c==v2) go=false;
          }
          return a;
        },[]);
    }
    
    console.log(reverseFromTo(letters,"D","B"))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search