An array containing an uneven number of elements

As I was exploring how to calculate the median value of an array, my initial step was determining whether the array had an odd or even number of elements.

  • If the number of elements is odd, then the middle element will be logged in the console.
  • If there's an even number of elements, I intended for the console to log 'Not an odd number of numbers'.

While I am aware that there might be simpler methods to find the median of an array, I prefer to try and solve it on my own. Currently, I'm stuck on why the number 1 is being logged in the second test case, despite the array having an even number of elements? It seems to work correctly in the first and third tests but not the second one...what could be going wrong?

function median (arr) {
  let sorted = arr.sort((a, b) => a-b)
  let midIndex = sorted.splice(0, sorted.length / 2)
  if (arr.length %2 != 0) {
    return midIndex[midIndex.length-1]
  } else {
    return "Not an odd number of numbers"
  }
  
}

try {
  let result = median([4, 8, 2, 4, 5])
  console.log(result)                   // -> 4

  result = median([-5, 1, 5, 2, 4, 1])  // -> 1
  console.log(result)

  result = median([5, 1, 1, 1, 3, -2, 2, 5, 7, 4, 5, 6])  // -> Not an odd number of numbers
  console.log(result)
} catch (e) {
  console.error(e.message)
}

Answer №1

Using the splice method directly impacts the length of the original array instead of creating a new one. This becomes evident when comparing the length of the array before and after calling splice.

function median (arr) {
  var initLength = arr.length;
  let sorted = arr.sort((a, b) => a-b)
  let midIndex = sorted.splice(0, sorted.length / 2)
  console.log(initLength, arr.length);
  if (arr.length %2 != 0) {
    return midIndex[midIndex.length-1]
  } else {
    return "Not an odd number of numbers"
  }
  
}

try {
  let result = median([4, 8, 2, 4, 5])
  //console.log(result)                   // -> 4

  result = median([-5, 1, 5, 2, 4, 1])  // -> 1
  //console.log(result)

  result = median([5, 1, 1, 1, 3, -2, 2, 5, 7, 4, 5, 6])  // -> Not an odd number of numbers
  //console.log(result)
} catch (e) {
  console.error(e.message)
}

This shows that splitting an array in half using splice with 6 elements results in an odd length of 3. To achieve the expected behavior, it is advisable to use the original array length:

function median (arr) {
  var initLength = arr.length;
  let sorted = arr.sort((a, b) => a-b)
  let midIndex = sorted.splice(0, sorted.length / 2)
  if (initLength %2 != 0) {
    return midIndex[midIndex.length-1]
  } else {
    return "Not an odd number of numbers"
  }
  
}

try {
  let result = median([4, 8, 2, 4, 5])
  console.log(result)                   // -> 4

  result = median([-5, 1, 5, 2, 4, 1])  // -> 1
  console.log(result)

  result = median([5, 1, 1, 1, 3, -2, 2, 5, 7, 4, 5, 6])  // -> Not an odd number of numbers
  console.log(result)
} catch (e) {
  console.error(e.message)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for making WebDriver pause until Sencha AJAX request finishes

While testing a page with Selenium WebDriver, I encountered an issue related to the Sencha JavaScript library being used on the underlying page. The problem arises when I input a value into a field and an AJAX call is made to validate that field. If the va ...

Encountering an error while trying to update a field using the $inc operator in

Currently, I am working on updating a field in my database to increment it each time like a counter. This will allow me to consistently receive the latest values. To achieve this, I have defined the following schema: var CounterSchema = new Schema({ _id: ...

Searching for an array of IDs in Mongoose

I have created an API using Express.js and mongoose to find users based on their ids in an array. // Here is the array of user ids const followedIds = follow.map((f) => f.followed); console.log(followedIds); // This will log [ '5ebaf673991fc60204 ...

Tips for reducing the size of the sidebar when navigating to a specific page

I have a sidebar that I want to minimize when the user enters the index page. There is a button in the sidebar for that: <a class="mobile-menu" id="mobile-collapse" href="javascript:"><span></a> How can I au ...

Steps to create an if statement using jQuery

.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) if ( ( item.parent_term_id == "16" ) ) { .append( "<a>" + (item.child_term ? item.child ...

What is the best way to search for unique fields in MongoDB using Node.js?

Explore the contents of my imageDetails database: > db.imageDetails.find() { "_id" : ObjectId("5a187f4f2d4b2817b8448e61"), "keyword" : "sachin", "name" : "sachin_1511554882309_1.jpg", "fullpath" : "Download/sachin_1511554882309_1.jpg" } { "_id" : Objec ...

How can we eliminate the 'www' in a URL using NodeJS and Express?

What is the best way to eliminate the 'www' in a URL using NodeJS + Express? For instance, when a client connects to , how can we automatically redirect them to without the 'www'? ...

Learn how to activate a JS native event listener using jQuery for the 'change' event

This question is unique from the one found at How to trigger jQuery change event in code. The focus here is on the interaction of jQuery with native event listeners, rather than jQuery event listeners. I am using addEventListener to bind a change event fo ...

Currently, I am compiling a list of tasks that need to be completed, but I am encountering a dilemma that is proving difficult to resolve

Recently delved into the world of Javascript and encountered a roadblock that I can't seem to overcome. Here's the snippet of code causing me trouble: add = document.getElementById("add"); add.addEventListener("click", () => { console.log("Ple ...

Why aren't the kittens loading in Next Js?

Following the guidance in the Next Js documentation, I created a next.config.js file to inform Next Js that I want to incorporate kittens into my app. The resource for the kittens can be found at: This is how the next.config.js file appears: module.expor ...

What is the best way to retrieve "text" from a function using JavaScript with Selenium web driver?

Update: The solution provided by Jonas has successfully resolved most of the issues. Currently, I am exploring options to utilize datepicker or sendkeys to set the date range as it continues to increment by one day each time the code is rerun. date_start = ...

Using Socket.io within express routes

Can I incorporate socket.io into an express route? This is how I envision it: Server app.js: app.get('/cool_page/', users.cool_page); users.cool_page: if (5 > 3) { socket.emit('first_connection', "true statement"); } Clien ...

PHP is unable to retrieve the form that is included on the page

Utilizing the same HTML code in multiple locations, I decided to streamline by placing it in a .php file and including it as needed. One instance involves incorporating this code within a form. This particular form contains one element, with the inclusion ...

Avoid having to refresh the page on create-react-app after uploading an image or file

Currently, my application is set up with 'create-react-app' and I am retrieving images from a folder within the 'src' directory. However, when a new image is uploaded through a form submission, it causes the page to reload as the image ...

math symbols in brackets of python array that can be compared

Imagine working with an array like this: numbers = [1,2,3,4,5,6,7] Now, let's take a look at this snippet of code: print(numbers[0<=3]) What is the purpose of this code? How does it function? ...

Hoping for a swift ajax response from the identical function

Even though similar questions have been asked multiple times, I have gone through many of them and still haven't found a solution to my specific issue. I am currently using a Wizard Jquery Plugin that triggers a function onLeaveAStepFunction when a s ...

Minimize a pop-up window and navigate to a different webpage

I have created a login/logout form that includes the option to delete my account. When I click the "Sterge cont" button, a pop-up window appears asking if I truly want to delete the account. If I select "NU," the account will not be deleted and the window ...

Unusual Glitch in Bootstrap 3 Dropdown Menu

I am currently developing a website using Bootstrap 3. I am encountering an issue with the navbar dropdown. When I click on the link, it changes to show "expand child menu" and "collapse child menu". To clarify, here is the image I am referring to: Initi ...

What could be causing the npm install command to not save packages in the /node_modules directory?

After running npm install to add a package, npm indicates that the installation was successful. However, upon checking the node_modules folder, I'm unable to locate the installed package. In order to access the package, I have resorted to using npm in ...

Guide on accessing elements such as inputs and selects in a changing form

I'm using a dynamic form that creates fields on the fly when the "+" button is clicked. This form isn't hardcoded into the document, but rather generated when the button is pressed. I'm wondering how I can access the form values. Should I ...