Filtering an array based on two specified boundary conditions

I have an array containing numbers from 1 to 7

const num = [1,2,3,4,5,6,7];

and two boundary values:

var first = 6
var second = 3

The desired output should be:

[6,7,1,2,3]

Explanation:

The resulting array should combine two sub-arrays:

  1. Numbers greater than or equal to 'first' (6) on the left side: [6, 7]
  2. Numbers less than or equal to 'second' (3) on the right side: [1, 2, 3]

I attempted to achieve this with the following code but the positions of elements are not as expected:

const result = num.filter((n,p) => {
  if(p >= num.indexOf(first)) {return n}
  else if(p <= num.indexOf(second)) {return n}
});

console.log(result) // [1,2,3,6,7]

An alternative method involves looping through the array twice, which is not efficient:

const num = [1,2,3,4,5,6,7];
var first = 6
var second = 3
var arr = []
num.forEach((n,p) => {
  if(p >= num.indexOf(first)) {arr.push(n)}
});
num.forEach((n,p) => {
  if(p <= num.indexOf(second)) {arr.push(n)}
});

console.log(arr) //[6,7,1,2,3]

Is there a better way to achieve this?

Answer №1

var numbers = [1, 2, 3, 4, 5, 6, 7];
var firstNum = 6;
var secondNum = 3;
const result = [
  ...numbers.filter((num) => num >= firstNum),
  ...numbers.filter((num) => num <= secondNum)
];
console.log(result); // [6,7,1,2,3]

Modified Version:

Iterate through the array once:

var numbers = [1, 2, 3, 4, 5, 6, 7];
var firstNum = 6;
var secondNum = 3;
var leftArray = [];
var rightArray = [];
numbers.forEach((num) => {
  if (num >= firstNum) leftArray.push(num);
  if (num <= secondNum) rightArray.push(num);
});
const finalResult = [...leftArray, ...rightArray];
console.log(finalResult); // [6,7,1,2,3]

Answer №2

Your inquiry appears to be quite unique, but the solution provided below should meet your needs:

const arr=[1,2,3,4,5,6,7];

// looking at positions of elements:
const getSubArraysPos=(ar,m,n)=>[...ar,...ar].slice(m-1,ar.length+n);
console.log(getSubArraysPos(arr,6,3))

// looking at array values:
const getSubArraysVal=(ar,m,n)=>[].concat.call(...ar.reduce((a,c)=>{
  if (m>n) { if(c>=m) a[0].push(c); else if (c<=n) a[1].push(c); }
  else if(c>=m && c<=n) a[0].push(c);
  return a }, [[],[]]));
  
console.log("6,3:",getSubArraysPos(arr,6,3));
console.log("5,2:",getSubArraysVal(arr,5,2));
console.log("2,5:",getSubArraysVal(arr,2,5))

The code may seem a bit concise, but the goal was to condense it into as few lines as possible.

Answer №3

To begin with, let me clarify the condition: the desired outcome entails merging 2 arrays:

  1. >= first on the left [6, 7]
  2. <= second on the right [1,2,3]

Result:1 & 2 = [6,7,1,2,3]


Approach:

An efficient method involves utilizing Array#reduce by initializing a result object as follows: {first:[], second: []}. Then, employ spread to concatenate the two arrays.

This approach ensures a time complexity of O(n).

const num = [1,2,3,4,5,6,7];
var first = 6, second = 3;

const result = num.reduce((acc, curr) => {
  if(curr >= first) acc.first.push(curr);
  if(curr <= second) acc.second.push(curr);
  
  return acc;
}, {first:[], second: []});
console.log([...result.first, ...result.second]);

Answer №4

While your initial attempt using the .filter method was somewhat successful, it's important to note that .filter doesn't have the ability to rearrange elements within an array.

To solve this issue, you can identify the index of the first specified value and use it as a reference point to extract part of the array. Then, locate the index of the second value, slice off the excess portion at the beginning of the array, and finally combine the two sections together.

const secondIdx = num.indexOf(second);
const firstIdx = num.indexOf(first, second+1);
const result = num.slice(firstIdx).concat(num.slice(0, secondIdx+1));

Answer №5

I feel the need to provide my own answer because the previous answers seem to have some sort of issue.

function arr(num, first, second){
 let arr = num.reduce((acc, v, i) => {
  let i1 = num.indexOf(first)
  let i2 = num.indexOf(second)
  if(i1 < i2 && i >= i1 && i <= i2) acc['a'].push(v)
  if(i1 > i2 && i <= i2){
    acc['t1'].push(v) 
  } 
  if(i1 > i2 && i >= i1) {
    acc['t2'].push(v) 
  }
  if(i1 > i2) acc['a'] = [...acc['t2'], ...acc['t1']]
  return acc
}, {a : [], t1: [], t2: []})

return arr['a']
}

let num = [1,2,3,4,5,6,7];
console.log(arr(num,2,5))
console.log(arr(num,5,2))
console.log(arr(num,3,6))
console.log(arr(num,6,3))

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 utilizing Async/Await within an expressjs router

Having trouble with Async/Await in my Nodejs project. I'm a beginner with Nodejs and facing an issue connecting to my mongodb collection through my repository. When I integrate my controller with the repository, I end up getting a null response. Take ...

Utilize PHP to extract specific values from this output

It's been a while since I've worked on PHP, and I'm struggling to understand the output of this code. It seems like there are multiple arrays involved, but different coding techniques lead to various errors. This is an API for a software too ...

Querying a Mongoose database in express.js using the "like" command for strings

Currently, I am trying to query my Mongoose database with a search parameter where the title matches the "customTitle" extracted from the URL. The search function works perfectly fine when searching for all items using Article.find(err, foundArticles) =&g ...

The InfoWindow on Google Maps is positioned above the Marker

My struggle lies in positioning the infowindow above my Google Maps API marker, as the infowindow keeps hiding the marker. I attempted using CSS to adjust the position of both elements, but unfortunately, it didn't have the desired effect. Here is th ...

Issue: The function is attempting to use the React Hook "useState" inappropriately

After updating the navbar on my NextJs site and making changes to the header, I encountered a build error that I couldn't resolve. The error message can be seen here: https://i.sstatic.net/jjXJG.png I tried researching and tweaking the code, especial ...

Exploring the concept of multiplying JSON arrays in Java can lead to a deeper understanding of how to

Seeking guidance on performing JSON Array Multiplication in Java. I'm attempting to multiply two JSON Arrays, [1,2] and [1898,0987]. Assistance would be greatly appreciated. ...

Adjust the position of the IMG to the left side

Struggling with some code and need some assistance: <script> function run() { document.getElementById("srt").value = document.getElementById("Ultra").value; } </script> <script> function ru ...

Displaying ember component in a separate template from its parent

Consider this scenario: I have an absolutely positioned sidebar containing additional absolute elements. Within the sidebar, there is a button that triggers a menu to appear: <button>Click me</button> {{#if shouldDisplayMenu}} {{view App.M ...

Divide a string into an array starting from the end

I have a unique phrase. var phrase = "LoremipsumdolorsitametconsectetuadipiscingelitSeddoeiusmodtemporincididuntutlaboreetaliqua"; I am interested in dividing it into chunks of 11 characters starting from the end. Currently, I use: function splitPhrase ...

Steps to keep a ByteArray unchanged in Kotlin

Is it possible to create an unmodifiable ByteArray in Kotlin? Similar to how we can create unmodifiable lists with Collections.unmodifiableList(byteList) ...

Titanium: Picture -> "automatically"

Imagine there is an image named hello.png with the dimensions of 200x100. A button is then created using this hello.png as shown below: var btn = Titanium.UI.createButton({ bottom : 50, backgroundImage : "images/hello.png", width:100, height:"auto"; }); w ...

Error Encountered: React - Material UI | Unable to locate the module: 'material-ui/Button'

Currently, I am utilizing a Material UI button in my React application page. import Button from 'material-ui/Button' <Button color="primary" variant="raised"> Group </Button> The following packages have ...

Is there a method within Google Sheets queries to combine the results of two columns and include additional text in the output? (I am aware that there is no built-in concatenation function in Sheets

Although Google Sheets queries do not have a concat method, I am looking for a workaround. I have tried the transpose method but it doesn't seem to work for my specific use case, so I am seeking assistance. While my actual source sheet is more comple ...

In React Js, I have noticed that when I incorporate a Select field, it only works when the value is an integer and not a string. It seems

Library version "material-ui": "^1.0.0-beta.35" react version: "react": "^16.2.0" Currently Functional: <MenuItem value={1}>Text</MenuItem> <MenuItem value={2}>Integer</MenuItem> <MenuItem value={3}>Inline</MenuItem> N ...

"Working with Node.js: Implementing a Static Variable in Module Ex

I am working on exporting a module that will store information in a hashtable to be accessed later. However, I am encountering difficulties in maintaining the consistency of the hashtable as a global variable throughout the application. Here is my current ...

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

Retrieve all documents from a Firebase User's collection

Recently, I created a Firebase cloud function where my goal is to access every user's internal collection named 'numbers' and examine each document within that collection for some comparisons. Do you have any insights on how I can achieve t ...

Using Angular 4 with Bootstrap dropdowns necessitates the use of Popper.js

I recently created an Angular 4 CLI app. After executing the following command: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066469697275727467764632283628362b64637267">[email protected]</a> jquery ...

"Optimizing Pagination in AngularJS: A Guide to Fixing

Can someone please help me with the code below? I am having an issue where my page 1 is not displaying any data and it only starts showing data from page 2. I've been trying to solve this for the past 3 hours with no success. I am new to angularjs and ...

Displaying arrays of strings in a JTextArea in Java

Greetings! I have successfully created a program that reads words from a text file and stores them in an array. Now, I am looking to display these words in a JTextArea that I have initialized, but I am unsure about the appropriate approach. The text file c ...