1

I have an object MyObject and one of its properties ItemIDs is an array of ints. I want to get a new array PageItemIDs that contains only part of the ints. It's for a pager; I pass in the page number PageNumber and I get the IDs of the items on the page. Suppose the page size is 20 items.

This is what I tried. It doesn't work because js works with references so I end up changing the array of the object.

PageItemIDs = MyObject.ItemsID;
PageItemIDs = PageItemIDs.splice(PageNumber * 20, 20);

And instead of getting the ItemIDs in the page, I end up with the ItemIDs not in the page.

I know I'm not that far off but if you can help that'd be nice.

Thanks.

Edit:

When I do

PageItemIDs = PageItemIDs.slice((PageNumber -1) * 20, 20);

it works for page 1 but for every other page, it returns an empty array.

Ok, I got it, nevermind.

 PageItemIDs = PageItemIDs.slice(PageNumber * 20, PageNumber * 20);

2 Answers 2

1

Use slice() instead of splice().

slice() returns a slice of the array, splice() changes the contents of the array in-place.

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

5 Comments

ok, slice keeps the original array intact. However PageItemIDs.splice(PageNumber * 20, 20); with PageNumber = 1 returns the same array with all the elements, instead of page 1.
@frenchie, slice() works differently than splice(). slice() takes the begin and end of the portion you want to slice. splice() takes an index and a count.
PageItemIDs = PageItemIDs.slice(1 * 20, 20); returns array 0 elements.
@frenchie, of course, because you're asking for all elements between 20 and 20. If you want all elements between 20 and 40, use slice(1 * 20, 40) instead.
ok, I got it: PageItemIDs = PageItemIDs.splice(PageNumber * 20, PageNumber * 20); Yes, I meant slice!
1
PageItemIDs = cloneObject(MyObject).ItemsID;
PageItemIDs = PageItemIDs.splice(PageNumber * 20, 20);

5 Comments

Object #<Object> has no method 'cloneNode'
could you post how MyObject is defined please?
It's defined as an array of ints.
Thank you, this is really kind of you ;)
what the ... THANKS! That's what is happening when you don't double check your code! There is a tipo + functional mistake here, correcting it right now!!

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.