1

Im trying to remove prev and next links from array. Using laravel vue3 inertiajs.

const splicedlinks = computed(() => {
    let prevIndex = props.links.meta.links
        .map((link) => link.label)
        .indexOf("« Previous");
    let nextIndex = props.links.meta.links
        .map((link) => link.label)
        .indexOf("Next »");

    props.links.meta.links.splice(prevIndex, 1);
    props.links.meta.links.splice(nextIndex, 1);

    return props.links.meta.links;
});

With this code i managed only to remove "« Previous", but not "Next »"

navigation image

Whats wrong with my code?

i explained what i tried in question.

1 Answer 1

1

Because the index of the "Next" element was changed after the first "splice" using.

JS Array splice method affects the source array. So the found elements indexes are not relevant after deleting an element by "splice" method.

You should to find "nextIndex" after deleting an element by "prevIndex"

Try this:

const splicedlinks = computed(() => {
    let prevIndex = props.links.meta.links
        .map((link) => link.label)
        .indexOf("« Previous");

    // Remove "Previous" button
    props.links.meta.links.splice(prevIndex, 1);

    // After "Previous" button deleting find index of "Next" button
    let nextIndex = props.links.meta.links
        .map((link) => link.label)
        .indexOf("Next »");
    
    // Remove "Next" button
    props.links.meta.links.splice(nextIndex, 1);

    return props.links.meta.links;
});

Also, you can simplify your code by using "findIndex" methods instead indexOf

Example:

let nextIndex = props.links.meta.links?.findIndex((link) => link.label === "Next »");
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much for the explanation and the code. Works!

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.