Tips for consolidating an array of numbers with close values

Looking to develop a function that can shrink a list of numbers based on a specified variation.

Variation Explanation:

The variation should cover a range above and below a given value. For example, if the variance is set at 100 for a value of 5460, it should encompass any number between 5410 - 5510 (50 below and 50 above).

For instance, when presented with this array:

[ 1576420754, 1576420756, 1576593554, 1581172759, 1581172764 ]

I wish to create a function filterSimilarValues(array, variance = 100)

This function should produce the following result:

[ 1576420756, 1576593554, 1581172764 ]

I've experimented with different approaches such as

const filterSimalarValues = (array, variance = 100) => {
    let filteredArray = [];

    for (let i = 0; i < array.length; i++) {
        const number = array[i];

        if (number >= number - (variance / 2) && number <= number + (variance / 2)) {
            return;
        }

        filteredArray.push(number);
    }

    return filteredArray;
};

Answer №1

To filter out numbers from an array based on the absolute difference between them and the next number being greater or equal to half of a specified variance, you can use the Array.filter() method along with Math.abs(). The last item in the array is included by default.

const excludeSimilarValues = (arr, variation = 50) => 
  arr.filter((num, index) => 
    index === arr.length - 1 ||
    Math.abs(num - arr[index + 1]) >= variation / 2
  )

const dataSet = [1357924680, 2468013579, 3579246801, 4680135792]

const myResult = excludeSimilarValues(dataSet)

console.log(myResult)

Answer №2

I suggest attempting something along these lines:

function removeSimilarValues(array, threshold = 100) {
    return array.reduce((uniqueValues, currentValue) => {
        const similarValueIndex = uniqueValues.findIndex(value => currentValue > value - threshold / 2 && currentValue < value + threshold / 2);
        if (similarValueIndex === -1) {
            uniqueValues.push(currentValue);
        } else {
            uniqueValues[similarValueIndex] = currentValue;
        }
        return uniqueValues;
    }, []);
}

It would also be beneficial to provide more specific details in your query as there are numerous potential scenarios that may not have been addressed.

Answer №3

Based on the explanation given and my interpretation of variance, the goal is to restrict the numbers within a specified range of variance. It is assumed that there are at least 2 elements present, but additional checks can be added for that scenario.

function filterSimilarValues(array, variance = 100) {
    const filteredArray = [];
    filteredArray.push(array[0]); // benchmark for comparison
    for (let i = 1; i < array.length; i++) {
        const number_lower_bound = array[i] - variance/2;
        const number_upper_bound = array[i] + variance/2;
        let bound_exist = false;
        for(let bound = number_lower_bound; bound <= number_upper_bound; bound++){
          if (filteredArray.includes(bound)) {
              bound_exist = true;
              break;
          }
        }
        if(!bound_exist){
            filteredArray.push(array[i]);
        }
      }
    
    return filteredArray;
};

Answer №4

This is my attempt at finding a solution, and while it works, I believe there may be room for improvement. Therefore, I am keeping an open mind and not settling on my own answer just yet.

const filterSimilarValues = (array, variance = 100) => {
  let filteredArray = [];

  array.forEach(number => {
    const start = number - (variance / 2);
    const end = number + (variance / 2);
    const range = Array(end - start + 1).fill().map((_, idx) => start + idx);
    const found = range.some(r => filteredArray.includes(r))

    if (!found) {
      filteredArray.push(number);
    }
  });

  return filteredArray;
};

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

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...

How can we add styles to text entered into a form input field in a targeted way?

Is there a way to apply styling to the second word entered into a form input text field after the user hits "enter" and the data is output? In this scenario, the text always follows the format of 3 numbers, followed by a space, and then a name. For examp ...

Tips on extracting information from several JSON response objects

I have the following ArrayList: JSONArray JMyDataList= new JSONArray(MyDataList); JSONArray JMyProjectData = new JSONArray(MyProjectData); MyDataList: contains data retrieved from a database with column names and data. response.setConten ...

You can eliminate the display flex property from the MuiCollapse-wrapper

Having trouble removing the display flex property from the MuiCollapse-wrapper, I did some research and found the rule name for the wrapper in this link https://material-ui.com/api/collapse/ I have been unsuccessful in overwriting the class name wrapper t ...

Tips for ensuring the footer always stays at the bottom of the page

I'm having an issue with keeping the footer pinned to the bottom of the page. I haven't applied any specific styles to the footer, just placed it at the end of the content. Everything looks great until there's a page with minimal content, ca ...

What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer Here is how I've modified the last line: 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottle of beer on the wall. How ...

What is the best way to include several IDs in a discord.js verification process?

I am attempting to create a basic script that verifies if the user's ID matches the one specified in the code. However, I'm struggling to understand how to achieve this. Any assistance from you all would be greatly appreciated. if(message.autho ...

What is the most effective way to alphabetically organize a Javascript array?

Is there a more professional way to sort people alphabetically by last name in an array? Here is the array I'm working with: const people = [ 'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd' ...

A Webpage that is permanently open, with no option to close it. The only option is to watch the video in

Currently, I am designing web pages for artists to showcase their work in an upcoming exhibition. The pages are ready, but now the artists are requesting that each piece be accompanied by a laptop displaying a single webpage with a video providing informat ...

Unable to bring in ES6 module to Vue's single file component

I am currently experimenting with ES6 modules and Vue.js, specifically single file components (SFC). To create my project, I utilized the Vue CLI with the webpack-simple template. I encountered an error that says "TypeError: Cannot read property 'name ...

Received an empty response while making an AJAX request - ERR_EMPTY_RESPONSE

I am trying to fetch real-time data from my database using Ajax, but I keep encountering an error. Here is the code snippet: <script> window.setInterval( function() { checkCustomer(); //additional checks.... }, 1000); function che ...

Is it possible to implement a "load more" feature with JSON data using the getJSON method?

Currently, I am working on the task of extracting objects from a JSON file and arranging them in a grid layout similar to masonry using Salvattore. While I successfully utilized this helpful tutorial to retrieve the data, my next challenge is to implement ...

Validation within nested Joi schemas

Need help validating a nested object conditionally based on a parent value. const schema = Joi.object({ a: Joi.string(), b: Joi.object({ c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Jo ...

Collection of arrays (Python/NumPy)

Working with Python and NumPy, I currently have two arrays that look like this: array1 = [1 2 3] array2 = [4 5 6] My goal is to create a new array: array3 = [[1 2 3], [4 5 6]] and add elements to it. For instance, if the new items to append are: array ...

How can I specify the exact width for Bootstrap 3 Progress Bars?

I have a single page that displays all my files in a table format, and I also have the count of open and closed files. My goal is to represent the percentage of closed files using a progress bar. The width of the progress bar should change based on this p ...

Executing NodeJS awaits in the incorrect order - When using Express with SQLite3's db.all and db.run, one await is prioritized over the other

Need help running asynchronous functions in .exports, getting promises, and using the results in subsequent async functions. Despite using awaits, the second function seems to execute before the first one. sales.js = const sqlite3 = require('sqlite ...

Unable to stop interval in Angular 5 application

My setInterval() function seems to be working fine as the timer starts, but I am encountering an issue with clearInterval(). It does not stop the timer when the counter value reaches 100 and continues running continuously. Any help or suggestions would be ...

Updating React state from another component - using useState

How can I efficiently update this state in React so that it changes when a specific button is clicked within the <FirstPage /> component? I'm struggling with finding the best approach to accomplish this. Any suggestions? const SignUp = () => ...

Select a picture at random from a directory

As a student embarking on an art project, I am in the process of selecting one out of 500 images to display on a webpage. My coding knowledge is quite limited, primarily focused on HTML and CSS, with only a basic understanding of JavaScript. I am encounter ...

Failing to utilize callback functions results in forgetting information

I am facing an issue with my code where changes in the parent component trigger a re-render of the child element. The Menu component is supposed to appear on right-click on top of the placeholder tag, but when it does, the entire parent component flicker ...