skip to Main Content

I am developing a webpage for myself where I am fetching links to tutorials using a API. The problem is, there are lots of links to click on.

Is there any way in JavaScript to divide the links in 3 groups and have 3 buttons where on click they open all the links in group? Like, "Open First 1/3", "Open Second 1/3" and "Open Last 1/3"?

I tried to divide the links.length with 3, but it gives me a the result in decimal, like when the links count is 31, I am getting 10.3333333333.

I am really clueless here. Any help will be appreciated. I know this question sounds kind of Do It For Me type, but believe me, its not. Just guiding me to the proper direction would be enough.

Thanks

3

Answers


  1. I think this would help.

     const linksCount = links.length;
    const linksPerGroup = Math.ceil(linksCount / 3);
    
    const firstGroupLinks = links.slice(0, linksPerGroup);
    const secondGroupLinks = links.slice(linksPerGroup, linksPerGroup * 2);
    const lastGroupLinks = links.slice(linksPerGroup * 2);
    
    corresponding links
    
    document.querySelector('#openFirstGroupButton').addEventListener('click', () => {
      firstGroupLinks.forEach(link => window.open(link));
    });
    
    document.querySelector('#openSecondGroupButton').addEventListener('click', () => {
      secondGroupLinks.forEach(link => window.open(link));
    });
    
    document.querySelector('#openLastGroupButton').addEventListener('click', () => {
      lastGroupLinks.forEach(link => window.open(link));
    });
    
    Login or Signup to reply.
  2. You can create chunck of links telling the size:

    let links = [];//links array
    let groupArr = [];
    const groupSize = 3;
    for (let i = 0; i < links.length; i += groupSize) {
      const chunk = links.slice(i, i + groupSize);
      groupArr.push(chunk);
    }
    
    Login or Signup to reply.
  3. due to the number of links is whole number, why don’t you round it up such as:

    if you have 20 links, you divide your links into 7-7-6 ?

    so you’ll do:

      const list = [
       // whatever lists you have here
      ]; 
      const take = Math.ceil(list.length / 3);
    
      const firstList = links.slice(0,take);
      const secondList = links.slice(take, take*2);
      const thirdList = links.slice(take*2); // this will take until the end
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search