0

My array of todos is like this:

[{id:1,text:"hello"},{id:2,text:"hey"},{id:3,text:"ho"},{id:4,text:"let's go"}]

I am just so confused I need help with this code like this, it's for pagination in react:

selectTodosToDisplay = (todos, { index1: 2, index2:3 }) => {
return [...todos.slice(index1, index2), 
        ...todos.slice(index2) ]
}

so with the above code I want to result into this

[{id:3,text:"ho"},{id:4,text:"let's go"}]

Maybe there's other methods for this? Help?

4 Answers 4

1

Array#slice returns a new array, so you don't need to spread it into a new one. The 2nd index should be 4, since Array#slice starts with the item in the 1st index, and ends with the item before the 2nd index. We can add 1 to the second index in the function.

const todos = [{id:1,text:"hello"},{id:2,text:"hey"},{id:3,text:"ho"},{id:4,text:"let's go"}];

const selectTodosToDisplay = (todos, { index1, index2 }) => todos.slice(index1, index2 + 1);

const result = selectTodosToDisplay(todos, { index1: 2, index2: 3 });

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0
var sample = [{ id: 1, text: "hello" }, { id: 2, text: "hey" }, { id: 3, text: "ho" }, { id: 4, text: "let's go" }];
var selectedID = 1;

function filterByID(item) {

    if (item.id == selectedID) {
        return true;
    }
    return false;
}

var arry = sample.filter(filterByID)

I hope it's work

Comments

0

Perfect use case for the JavaScript spread syntax:

const [first, second, ...rest] = [{id:1,text:"hello"},{id:2,text:"hey"},{id:3,text:"ho"},{id:4,text:"let's go"}];

console.log(rest);

Comments

0
selectTodosToDisplay = (todos, { index1: 2, index2:3 }) => todos.slice(index1, index2 + 1)

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.