0

As you can run this code snippet my array.slice() seems to not work or I might have messed some other logic. After checking with different approach to extract out the array (using push) the whole code is working fine . But on this approach with slice() it doesn't extract out the copy of "width" array.

What am I missing here?

function serviceLane(cases,width) {
    console.log(cases)

    var b = cases.map((e,i,ar)=>{
        
        var entry = e[0];
        var exit = e[1];
        console.log(entry)
        console.log(exit)

        console.log(width)
       // var p =[];
        var v=exit-entry+1;
       
       var p = width.slice(entry,v)
        console.log(p);


        var m =Math.min(...p)
        console.log(m)
        return m ;

    })

    console.log(b)

    return b;
}

console.log(serviceLane([ [ 0, 3 ], [ 4, 6 ], [ 6, 7 ], [ 3, 5 ], [ 0, 7 ] ],[ 2, 3, 1, 2, 3, 2, 3, 3 ]))

2
  • can you explain the real problem you are trying to solve rather explaining what you think is not working? also when entry > v array will be empty and Math.min()(Math.min(...[]) in your case) with no params return Infinity. Commented Sep 13, 2020 at 14:50
  • @AZ_ Why is slice() as in here, var p = width.slice(entry,v) not working as it prompts empty array at console. You can see in the snippet also. Commented Sep 13, 2020 at 15:00

1 Answer 1

1

Read the docs of Array.slice([begin, [end]])

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Docs

But you are using it like width.slice(begin, elemsToTake) Thus for instance, in the second iteration of map, you are doing width.slice(4,3) which means, extract from the array beginning at index 4, ending (not including) at index 3 which results of course in an empty array, because the end index is smaller than the begin.

You probably want to do

var p = width.slice(entry, exit +1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.