Use a Google Script to display a dynamic dropdown menu in a HTML form Google Sheet Doc

I need help with my first Google Script. I have a dropdown menu that displays a list of items from my Google Sheets doc which works perfectly.

The first menu displays a list of media types which removes any duplicates and sorts them out alphabetically. I’m now trying to add another dropdown menu that’s dynamic so when the user selects a media type, only the brands for that media type show. Once the user selects from the second menu, I want the price to appear at the bottom of the form that matches the media type and brand.

enter image description here

First dropdown menu (this is working perfect)

function getColors() { 
  const sheet = SpreadsheetApp.openById("123456").getSheetByName("Vinyl-Prices");

  const colName = 'Media Type';
  const colNum = getColorColNumByName(colName);
  if (colNum === null) {
    Logger.log('Column ' + colName + ' was not found!');
    return [];
  }

  const firstRow = 2;
  const lastRow = sheet.getLastRow();

  // get all values from column
  const columnData = sheet.getRange(firstRow, colNum, lastRow).getValues().flat();

  // filter values on duplicates
  return columnData.filter((el, i) => i === columnData.indexOf(el) && el !== '').sort()
}

function getColorColNumByName(colName, row = 1) {
  const sheet = SpreadsheetApp.openById("123456").getSheetByName("Vinyl-Prices");
  
  const [data] = sheet.getRange(row, 1, row, sheet.getLastColumn()).getValues();
  const col = data.indexOf(colName);

  // adding 1 because column nums starting from 1
  return col === -1 ? null : col + 1;
}

That works as it should.

I now have 2 scripts for the second part of the form. The first displays the list of brands but it’s not linked to the first menu meaning every brand shows whether it matches or not.

Here:

function getFruits(color) { 
  const sheet = SpreadsheetApp.openById("123456").getSheetByName("media Costs");

  const colName = 'Brand';
  const colNum = getFruitColNumByName(colName);
  if (colNum === null) {
    Logger.log('Column ' + colName + ' was not found!');
    return [];
  }

  const firstRow = 2;
  const lastRow = sheet.getLastRow();

  // get all values from column
  const columnData = sheet.getRange(firstRow, colNum, lastRow).getValues().flat();

  // filter values on duplicates
  return columnData.filter((el, i) => i === columnData.indexOf(el) && el !== '').sort()
}

The second script works as it should but it doesn’t do other stuff that I need it to do such as list the items in alphabetical order or allow me to select the column by name.

function getFruits(color) { 
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Vinyl Costs");
  var getLastRow = sheet.getLastRow();
  var return_array = [];
  for(var i = 2; i <= getLastRow; i++)
  {
      if(sheet.getRange(i, 1).getValue() === color) {
        return_array.push(sheet.getRange(i, 2).getValue());
      }
  }


  return return_array;  
}

Finally ,I need the form to display the price at the bottom based on what media and brand was selected. I have attached my html for but why can’t I figure the second form out and add the price at the end, this is simple stuff.

HTML form

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
    function GetFruit(color) 
    {
    
    google.script.run.withSuccessHandler(function(ar) 
    {

    console.log(ar);
    
    fruit.length = 0;
    
    let option = document.createElement("option");
    option.value = "";
    option.text = "";
    fruit.appendChild(option);
    
    ar.forEach(function(item, index) 
    {    
      let option = document.createElement("option");
      option.value = item;
      option.text = item;
      fruit.appendChild(option);    
    });
    
    }).getFruits(color);
    
    };
  </script>  
  </head>
  <body>
    <h1>Web App Dependent Drop Down</h1>
    <?var url = getUrl();?>
    <form method="post" action="<?= url ?>" >
      <label style="font-size: 20px" >Name</label><br>
      <input type="text" name="name" style="font-size: 20px" /><br><br>
      
      <label style="font-size: 20px" >Colors</label><br>
      <select name="color" style="font-size: 20px" onchange="GetFruit(this.value)" >
      <option value="" ></option>
      <? for(var i = 0; i < colors.length; i++) { ?>      
      <option value="<?= colors[i] ?>" ><?= colors[i] ?></option>
      <? } ?>
      </select><br><br>
      <label style="font-size: 20px" >Fruit</label><br>
      <select name="fruit" id="fruit" style="font-size: 20px" >
      </select><br><br>
      <label style="font-size: 20px" >Blank - Price will got here</label><br>
      <select name="fruit2" id="fruit2" style="font-size: 20px" >
      </select><br><br>
      <input type="submit" name="submitButton" value="Submit" style="font-size: 20px" /> 
      <span style="font-size: 20px" ><?= message ?></span>      
    </form>
  </body>
</html>

React- ContectApi

Getting empty array in useContext in section component initially due to which the section component is empty .Please help me fix this.

//this is my context component


export const Products = createContext();

export const ProductContext = (props) => {
  const [state, setState] = useState([]);
  useEffect(async () => {
    try {
      const res = await fetch("https://demo7303877.mockable.io");
      const items = await res.json();
      console.log(items);
      // console.log(items.products);
      setState(items);
    } catch (err) {
      console.log(err);
    }
  }, []);

  return (
    <Products.Provider value={[state, setState]}>
      {props.children}
    </Products.Provider>
  );
};

//getting empty array initially in state
//this is section component

import React, { useContext, useState } from "react";
import { Products } from "../Context/ProductsContext";

function Section() {
  const [state, setState] = useContext(Products);
console.log (state) //this return an empty array initially

return (
    <div>
      {state.length > 1 &&
        state.products.map((p) => {
          return <p> {p.brand}</p>;
        })}
    </div>
  );
}

export default Section;

can i use same show/hide button on 2 different sections or divs

I’m attempting to use the same ID, but it’s not working. I duplicated the script and added an extra character to make it unique, but it didn’t work. Also, when I show the hidden columns (“I am using bootstrap 5 col grid”), the images display inline, and I want them to match the grid. I altered the display value in the script, and tried many other values, but none of them work; they all display inline.Last question, if you look at my code, I’m using a down arrow png just to make it look nice, but when you click it, the show less button displays the same png icon, which is logical, but I want to change it to another png that shows an up arrow, but I’m not sure how to do it. I figured out how to change the color of the show less button, but not the image/icon arrow.Thank you very much for any assistance.

 function toggleText() {
  var showMoreText = document.getElementById("more");  
  var buttonText = document.querySelector("#moreButton p");
  
  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-column-group";
    buttonText.innerHTML = "Show More";    
    buttonText.classList.remove('less')
  } else {
    showMoreText.style.display = "table-column-group";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less')
  }
}
.pink{
    color: #FF7B5F;
  }

  #more {
    display: none;
}

  #moreButton{
    background-color:transparent;
    border-color: transparent; 
   }


   .less{
       color: #FF7B5F;
   }
<html>

<head>
 <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
 </head>
 
 <body> 
 <container>
 <div id="startpoint"></div>
            <div id="more">
            <div class="clients BRANDING col-6 col-md-4 col-lg-3 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://www.wrappixel.com/demos/ui-kit/wrapkit/assets/images/team/t3.jpg" width="150" alt="Logo">
                  <figcaption class="product-desc"><P>text</P></figcaption>
                  <figcaption class="product-desc2"><h4>text</h4></figcaption>
                </figure>
              </a>
            </div>
            
            <div class="clients BRANDING col-6 col-md-4 col-lg-3 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://www.wrappixel.com/demos/ui-kit/wrapkit/assets/images/team/t3.jpg" width="150" alt="Logo">
                  <figcaption class="product-desc"><P>text</P></figcaption>
                  <figcaption class="product-desc2"><h4>text</h4></figcaption>
                </figure>
              </a>
            </div>
          </div>
          <button onclick="toggleText()" id="moreButton">
           <p class="pink">Show More</p> 
           <img class="more" src="./images/downarrow.png" alt="">
          </button>
          </div>
        </div>  
        <section class="team text-center bg-dark py-1">
        
              <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  </container>
  
        </body>
        </html>
        

How can you dynamically switch SignalR hubs

I have 2 hubs that live on 2 different servers. Ideally I would like my series of webpages to connect to attempt to connect to 1 of these hubs, then if it fails switch to the other hub. Is this possible at all.

I can’t use the traditional method to connecting to the hub like so:

<script id="hubScript" src="IP:port/signalr/hubs"></script>
    $.connection.hub.url = SIGNALR_HUB_SERVER_1;
    srv = $.connection.tcpHub;

since I don’t know which hub I will be connecting to, or which hub will be alive.

Example of code that I have tried for reference

   if (document.head.getElementsByTagName("script").item(i).src == SIGNALR_HUB_SERVER_1 + "/hubs") {
        $.connection.hub.url = SIGNALR_HUB_SERVER_1;
   }
   else if(document.head.getElementsByTagName("script").item(i).src == SIGNALR_HUB_SERVER_2 + "/hubs") {
        $.connection.hub.url = SIGNALR_HUB_SERVER_2;
   }

When I try and connect using this code I get the error: “Error loading hubs. Ensure your hubs reference is correct”. This is because my script tag that contains the url is not the same as the url that I am trying to connect to.

Discord.js Bot Error: TypeError: voice_channel.join is not a function (Discord.js V13.6.0)

I have been following a tutorial by CodeLyon on how to create a Discord music bot. After following it step by step when he tests the bot at the end of the video, it works fine, whereas when I try and test my bot, I am given this error in the terminal.

TypeError: voice_channel.join is not a function

Has this function changed in a new version of Discord.js? There have been a couple of times where I’ve had to Google a broken function to find the updated code as the tutorials are just over a year old, though this time I can’t find anything.

Here is a snippet of the code which is giving me the TypeError, I’ve scanned through the SourceBin he provided in the description but it appears that I’ve coded everything correctly, as well as installed all the packages provided in the video.

//Establish a connection and play the song with the video_player function.
try {
    const connection = await voice_channel.join(); //Error is on this line
    queue_constructor.connection = connection;
    video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
    queue.delete(message.guild.id);
    message.channel.send('There was an error connecting...');
    throw err;
}
} else {
    server_queue.songs.push(song);
    return message.channel.send(`**${song.title}** added to queue!`);
}

Clicking button changes View in .NET/MVC web app

I’m very new to .Net development, and I’m working on a ticket. The goal is that when the user clicks a button, they’ll be redirected to another page on our website (that i have to create)- this new page will have the same header/footer/css but different elements in the body.

my question is: how do i go about creating this? do i need a new method in the controller to return a new view? Do i need a new JS file?

There’s so many different parts to .NET and i’m struggling to understand where the code goes

any advice would be much appreciated!!

Allocate Shares Following Instruction List

Below is the coding question:

Assuming I bought 165 shares at the following rate:

Number of shares Price per share
23 2.5
47 2.54
45 2.56
50 2.6

Allocate the 165 shares using the following instruction:

  • 50 shares to account1,
  • 53 shares to account2,
  • 17 shares to account3,
  • 45 shares to account4.

All of the account must be allocated based on “Lowest Price First Top to Bottom”

I’ve gotten this far with it:

let shares = [
    { numOfShares: 23, price: 2.5 },
    { numOfShares: 47, price: 2.54 },
    { numOfShares: 45, price: 2.56 },
    { numOfShares: 50, price: 2.6 },
  ];
  let allocate = [
    { numToAllocate: 50, name: "account1" },
    { numToAllocate: 53, name: "account2" },
    { numToAllocate: 17, name: "account3" },
    { numToAllocate: 45, name: "account4" },
  ];

  for (let eachAllocate of allocate) {
    let num = eachAllocate.numToAllocate;
    let numOfShares = 0;
    for (let eachShare of shares) {
      num -= eachShare.numOfShares;
      if (num > 0)
        console.log(
          `Account: ${eachAllocate.name}, Quantity Assigned: ${eachShare.numOfShares}, trade price: ${eachShare.price}`
        );
      if (num <= 0) {
        console.log(
          `Account: ${eachAllocate.name}, Quantity Assigned: ${
            num + eachShare.numOfShares
          }, trade price: ${eachShare.price}`
        );
        numOfShares = parseInt(num * -1);
        console.log(numOfShares);
        break;
      }
    }
  }

Output:

Account: account1, Quantity Assigned: 23, trade price: 2.5
Account: account1, Quantity Assigned: 27, trade price: 2.54
20
Account: account2, Quantity Assigned: 23, trade price: 2.5
Account: account2, Quantity Assigned: 30, trade price: 2.54
17
Account: account3, Quantity Assigned: 17, trade price: 2.5
6
Account: account4, Quantity Assigned: 23, trade price: 2.5
Account: account4, Quantity Assigned: 22, trade price: 2.54
25

So here my problem is, I am not quite sure how to enforce it so each time I go through eachAllocate it doesn’t start from beginning, it continues from where it’s left off.. So 20, 17, 6, 25 are numbers where it’s left off from previous allocation…

Access JavaScript filter function in object of functions: Cannot read properties of undefined (Vuex store)

The problem in my vuex store index.js:

I want to filter an array with another array. If I access the filter function in its object I get an:

TypeError: Cannot read properties of undefined (reading 'includes')
    at aspect_ratio (index.js?9101:72:1)

I have all my filter functions in an object like this:

export const filter_functions = {
  form_factor_landscape: (obj) => {
    return obj["Form Factor"] === "Landscape";
  },
  form_factor_portrait: (obj) => {
    return obj["Form Factor"] === "Portrait";
  },
  aspect_ratio: (obj) => state.current_features.includes(obj["Aspect Ratio"]),
};

In my getters I want to access the aspect_ratio filter like this:

export const getters = {
  filtered_items(state) {
      const filteredArray = [...state.allHandhelds].filter(
        filter_functions[state.current_sort]
      );
      return filteredArray.filter(filter_functions.aspect_ratio);
    } 
  },
};

my state is like this:

export const state = () => ({
  current_sort: "all_handhelds",
  current_features: ["a", "b", "c"],
  allHandhelds: [],
});

My thoughts:

It seems like there is some problem with accessing the object with the filter functions. Or more precisely accessing the current_features array from the state.

Strangely if I just take the filter function outside the object and directly embedd it everything works. Like this:

return filteredArray.filter((obj) => state.current_features.includes(obj["Aspect Ratio"]));

Any idea what I’m doing wrong?

How can i add new elements at the beggining while i am scrolling?

I have this code where when i am scrolling down i am appending new elements

<div class="card-container">
        <div class="card show">First card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
        <div class="card">card</div>
</div>

JS

const cards = document.querySelectorAll('.card');
const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
        entry.target.classList.toggle('show', entry.isIntersecting);
    })
})

const lastCardObserver = new IntersectionObserver(entries => {
    const lastCard = entries[0];
    if(!lastCard.isIntersecting) return
    loadNewCards();
    lastCardObserver.unobserve(lastCard.target);
    lastCardObserver.observe(document.querySelector('.card:last-child'));
}, {rootMargin: '200px'})

const cardContainer = document.querySelector('.card-container');
function loadNewCards() {
    for(let i = 0;i < 10;i++) {
        const card = document.createElement('div');
        card.textContent = 'new card';
        card.classList.add('card');
        card.classList.add(`card-${i}`);
        observer.observe(card);
        cardContainer.append(card);
    }
}

cards.forEach(card => {
    observer.observe(card);
})

lastCardObserver.observe(document.querySelector('.card:last-child'))

EVERYTHING WORKS FINE

but i need now when i am at the beggining at the element which is on the viewport, while i scroll up
to add new elements so to detect that i am scrolled to the first element in the viewport

How can i do that

Displaying current value of order (checkbox problem)

I have a problem with my Formik and checkbox. I wanted to display the current value of the order which te checked values would determine. The problem is that when I tried to either call function sumProducts or addChecked inside Formik there:

{(values) => {
                    
  sumProducts(values.values.checked)

it doesn’t work correctly. It seems like it multiplies the original price * 3.
Anyway I wouldn’t like to use sumProducts immedietaly, because at first I wanted to determine whether I unchecked or checked the checkbox. That’s why I created the addChecked function, but when after checking if the value is being checked or unchecked and wanting to call the function sumProducts inside addChecked I have error that I went into infinite loop/renders.

import { Formik,Field,Form,ErrorMessage } from 'formik';
import React, {useState} from 'react';
import {v4 as uuidv4 } from 'uuid';
import {connect} from "react-redux";
import {Order} from "../../ducks/orders/OrderInterfaces";
import {addOrder} from "../../ducks/orders/OrderActions";
import {RootStore} from "../../ducks/RootReducer";
import {Product} from "../../ducks/products/ProductsInterfaces";
import {User} from "../../ducks/users/UserInterfaces";

interface OrdersFormProps {
    addOrder: (order: Order) => void,
    products: Product[],
    users: User[]

}

const ProductsForm = ({addOrder, products, users}: OrdersFormProps) => {

    interface OrdersFormValues {
        id: string,
        client: string,
        checked: Array<string>

    }

    const initialValues: OrdersFormValues = {
        id: uuidv4(),
        client: '',
        checked: [],

    }

    const handleSubmit = (values: OrdersFormValues) => {
        console.log(values)
      // addOrder(values)
    }
    const [checked,setChecked] = useState<string[]>([])
    const [currentPrice,setCurrentPrice] = useState(0)

    const addChecked = (prod: string) => {
        checked.find(product => product === prod) ? checked.filter(product => product !== prod)
            : setChecked(prev => [...prev,prod])
        //sumProducts(checked)
    }
    const sumProducts = (prod: Array<string>) => {
        const sum = prod.reduce((acc,curr) => {
            const currProduct = products.find(product => product.id === curr)
            if (currProduct) {
                return acc+currProduct.price
            }
            return acc
        }, 0)
        setCurrentPrice(currentPrice => currentPrice+sum)
    }
    return (
        <div>
            <Formik
                initialValues={
                    initialValues
                }
                onSubmit={(values, {resetForm}) => {handleSubmit(values); resetForm({values: undefined})}}
                enableReinitialize={true}>
                {(values) => {
                    //sumProducts(values.values.checked)
                    return (
                        <Form>
                            <label htmlFor="client">Client:
                                <Field name="client" as="select">
                                    <option disabled value="">(select a client)</option>
                                    {users && users.map(user => (
                                        <option value={user.id} key={user.id}>{user.firstName} {user.lastName}</option>
                                    ))}
                                </Field>
                                {products && products.map(product =>
                                    <label>
                                        <Field type="checkbox" name="checked" value={product.id} key={product.id} /> {product.name}
                                    </label>
                                )}
                            </label>
                            <button type="submit">
                                Submit
                            </button>
                        </Form>
                )}}

            </Formik>
            <p>Current price of order: {currentPrice}</p>

        </div>
    );
};

const mapStateToProps = (state: RootStore) => {
    return {
        products: state.products.products,
        users: state.users.users
    }

}

const mapDispatchToProps = {
    addOrder
}

export default connect(mapStateToProps,mapDispatchToProps)(ProductsForm);


Adding tests for waitFor util to wait the call back with retry when the callback failed

export const waitFor = async cb => {
  let c = 0
  async function f () {
    console.log('inside f')
    try {
      return await cb()
    } catch (error) {
      if (c < 10) {
        c += 1
        setTimeout(f, 500)
      }
    }
  }
  const result = await f()
  return result
}

I’ve this util to wait my callback, and to retry 10 times in 500ms delay, and want to add a test for waitFor util.

describe('testUtilis', () => {
  it('should wait till callback resolves', async () => {
    const cb = async () => {
      await sleep(500)
      return 'Hello'
    }

    const result = await waitFor(cb)
    expect(result).toBe('Hello')
  })

  it('should retry a failed callback', async () => {
    const globalNow = Date.now()

    const getByText = async () => {
      const now = Date.now()

      const gapInMilliseconds = now - globalNow
      if (gapInMilliseconds <= 2000) throw new Error('less than 2 seconds')

      return 'Hello'
    }

    const result = await waitFor(getByText)
    expect(result).toBe('Hello')
  })
})

I tried to throw an error when the callback is calling for 2 seconds, and to return ‘Hello’ after then, but the callback is calling only one time and the test is failing. What did I overlook here or a different approach for testing the retry part of waitFor.

  it('should upload a pdf on "Upload voucher here" text click', async () => {
    const { getByText } = mountComponent({
      certificate: {
        certificateName: 'Computer science',
        voucherStatus: VOUCHER_STATUS.OUTSTANDING_VOUCHER
      }
    })

    const fileName = 'hello.pdf'

    const file = new File(['"(⌐□_□)"'], fileName, {
      type: 'application/pdf'
    })

    const uploadText = getByText('Upload voucher here')

    fireEvent.change(uploadText, {
      target: {
        files: [file]
      }
    })

    await waitFor(() => {
      expect(getByText('hello.pdf')).toBeInTheDocument()
    })
  })

Test file for fileUpload and it works fine.

{
   selectedFile && (
       <StyledFileName>
          {selectedFile.name}
       </StyledFileName>
   )
}

A snippet in the component, where selectedFile is a state to store the user selected file(event.target.files[0])).

Hitting Digest already called on cryptoJS during unit testing

import crypto from 'crypto';

export const getChecksum: (_: PathLike) => Promise<string> = (path: PathLike) =>
  new Promise(resolve => {
    const hash = crypto.createHash('md5');
    const input = fs.createReadStream(path);

    input.on('data', chunk => {
      hash.update(chunk);
    });

    input.on('close', () => {
      resolve(hash.digest('hex'));
    });
  });

Given the function, it can accept a file path, and perform hash.update while streaming the file, I’m trying to write an unit test like below

describe('getChecksum()', () => {
  afterEach(() => {
    vol.reset();
  });

  it('should generate consistent checksum', async () => {
    vol.fromJSON(
      {
        './some/README.md': '1',
        './some/index.js': '2',
      },
      '/app'
    );

    const result = await getChecksum('/app/some/index.js');
    expect(result).toBe('c81e728d9d4c2f636f067f89cc14862c');
  });
});

From the Unit Test above, assertion was able to perform correctly, however, I’m hitting error below

  ● getChecksum() › should generate consistent checksum

    Error [ERR_CRYPTO_HASH_FINALIZED] [ERR_CRYPTO_HASH_FINALIZED]: Digest already called

      63 |
      64 |     input.on('close', () => {
    > 65 |       resolve(hash.digest('hex'));
         |                    ^
      66 |     });
      67 |   });
      68 |

Not too sure which part has gone wrong?

Given a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it which sum to k

I’m tacking this problem and I can’t seem to arrive at the correct solution. The question is:

“Given a list of n integers arr[0..(n-1)], determine the number of different pairs of elements within it which sum to k. If an integer appears in the list multiple times, each copy is considered to be different; that is, two pairs are considered different if one pair includes at least one array index which the other doesn’t, even if they include the same values.”

My approach is that I’m building a map that contains each number in the array and the number of times it occurs. Then I iterate over the map to find my answer.

function numberOfWays(arr, k) {
  let output = 0;
  let map = {};

  // put values and # of occurences into map
  for(let i = 0; i < arr.length; i++) {
    let key = arr[i];
    if(!(key in map)) {
      map[key] = 1;
    } else {
      map[key]++;
    }
  }
  
  for(let key in map) {
    let difference = k-key
    if((difference) in map) {
      if(k/2 === key) {
        output += map[key]*(map[key]-1)/2;
      } else {
        output += map[key] * map[key] / 2;  // divide by 2 so that pairs aren't counted twice
      }
    }
  }

  return output;
}

The two test cases are:
var arr_1 = [1, 2, 3, 4, 3]; expected result: [2] — I’m getting [3]

var arr_2 = [1, 5, 3, 3, 3]; expected result: [4] — I’m getting [5.5]

I’m definitely doing something wrong in my calculations, but I can’t seem to wrap my ahead around it.