Home > database >  How to return every 2 item in array?
How to return every 2 item in array?

Time:09-01

I have an array of objects :

const routes = [
{ id: 1, path: "/", element: <HomePage /> },
{ id: 2, path: "/about", element: <AboutPage /> },
{ id: 3, path: "/review", element: <ReviewPage /> },
];

I have to loop though the array by the id and get every 2 item. So by explanation the first item would be : id : 1 then we do 2 and next item is id:3

third item : id : 2

fourth item : id : 1

fifth item : id : 3 etc...

How would that be implemented?

CodePudding user response:

I think that you will be in need to use a while until the condition you want and take an value like i = 1 (for example). Next you should take your element id = i and add to i 2. And to finish you just need to verify if (i > 3) in this case you set i = i - 3. The code should work, here is an example :

const routes = [
{ id: 1, path: "/", element: <HomePage /> },
{ id: 2, path: "/about", element: <AboutPage /> },
{ id: 3, path: "/review", element: <ReviewPage /> },
];

i = 1
while (True) {
    console.log(routes[i]);
    i  = 2;
    if (i > 3) { i -= 3}
}

CodePudding user response:

You can use closure in this case

const routes = [{id:1,path:"/",element:"<HomePage />"},{id:2,path:"/about",element:"<AboutPage />" },{ id:3,path:"/review",element:"<ReviewPage />" }];

const makeNext = (size, step = 2) => {
    let i = size - step;
    
    return () => {
        i  = step;
        if (i >= size) i -= size; 
        return i;
    }
};

const nextId = makeNext(routes.length);

console.log(routes[nextId()]);
console.log(routes[nextId()]);
console.log(routes[nextId()]);
console.log(routes[nextId()]);
console.log(routes[nextId()]);
.as-console-wrapper { max-height: 100% !important; top: 0 }

CodePudding user response:

I believe that this could be of help to you.

https://jsfiddle.net/codyrowirthpaige/gr3cy4ek/

const arr = [
1,2,3,4
    ];
// return every second item in the array
function everySecond(arr) {
    var newArr = [];
    for (var i = 0; i < arr.length; i  = 2) {
        newArr.push(arr[i]);
    }
    console.log(newArr)
    return newArr;
    }
    
everySecond(arr);

  • Related