Locate the subsequent elements in an array using Angular 2

In my Angular 2 application, I am working with an array of objects. My goal is to retrieve the next five elements in the array that have a key greater than the one provided.

If I input key = 1, the expected output should be values with keys [2, 3, 4, 5, 6]
If I input key = 2, the expected output should be values with keys [3, 4, 5, 6, 7]
If I input key = 10, the expected output should be values with keys [11, 12, 13, 14]
If I input key = 12, the expected output should be values with keys [13, 14]

[
{key: "1", value: "value1"}
{key: "2", value: "value2"}
{key: "3", value: "value3"}
{key: "4", value: "value4"}
{key: "5", value: "value5"}
{key: "6", value: "value6"}
{key: "7", value: "value7"}
{key: "8", value: "value8"}
{key: "9", value: "value9"}
{key: "10", value: "value10"}
{key: "11", value: "value11"}
{key: "12", value: "value12"}
{key: "13", value: "value13"}
{key: "14", value: "value14"}
]

Answer №1

let info = [
{key: "a", value: "infoA"},
{key: "b", value: "infoB"},
{key: "c", value: "infoC"},
{key: "d", value: "infoD"},
{key: "e", value: "infoE"},
{key: "f", value: "infoF"},
{key: "g", value: "infoG"},
{key: "h", value: "infoH"},
{key: "i", value: "infoI"},
{key: "j", value: "infoJ"},
{key: "k", value: "infoK"},
{key: "l", value: "infoL"},
{key: "m", value: "infoM"},
{key: "n", value: "infoN"}
]   

 getNextThree = (key) => { 
      const index = info.findIndex(item => item.key == key); // no type checking
      if (index > -1) { // if key exists in data
         return info.slice(index + 1, index + 4).map(val => parseInt(val.key))
      } else {  // if key doesnt exist in data
         return []
      }
    }

console.log(getNextThree("a"));
console.log(getNextThree("b"));
console.log(getNextThree("j"));
console.log(getNextThree("l"));

Answer №2

To exclude all items with a key lower than the specified key in JavaScript, you can utilize the filter function and subsequently apply splice to limit the array to 5 elements. Check out the code snippet below.

getNextEls = (key) => {

  var arr = data.filter((x) => {
    return parseInt(x.key) > key
  })

  arr = arr.length > 5 ? arr.slice(0, 5) : arr
  return arr
}

If you only wish to retrieve the keys or values from those items, you can incorporate the following conditions within the filter logic.

if (parseInt(x.key) > key){
  return parseInt(x.key) //to get the key.
  return x[x.key] //to acquire the values
}

var data = [{
    key: "1",
    value: "value1"
  },
  {
    key: "2",
    value: "value2"
  },
  ...
]

getNextEls = (key) => {

  var arr = data.filter((x) => {
    return parseInt(x.key) > key
  })
  
  arr = arr.length > 5 ? arr.slice(0, 5) : arr
  return arr
}

console.log(getNextEls(1))
console.log('-----')
console.log(getNextEls(2))
console.log('-----')
console.log(getNextEls(3))
console.log('-----')
console.log(getNextEls(12))

Answer №3

let newArray = [];
information.forEach(function (object) {
    if (object.id > passedKey && count <= 5) {
        newArray.push(object.data);
        count++;
    }
});
console.log(newArray[]);

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

Incorporate New Element into the Express Request Object

I am attempting to enhance the Express request object by adding a property called "forwardingUrl". To achieve this, I utilized declaration merging in a file named ./typing.d.ts: declare namespace Express { export interface Request { forwardingUrl: ...

Can a client receive a response from server actions in Next.js 13?

I'm currently developing a Next.js application and I've created an action in app/actions/create-foo-action.js. In this server action, I am attempting to send a response back to the client. import { connectDB } from "@utils/database" imp ...

Is compiling inline sass possible with npm?

Looking for a simple method to achieve this task? I've experimented with sass, node-sass, and tinysass without success. My goal is to compile inline sass in JavaScript, much like the code snippet below: import sassPkg from 'sass-pkg' const ...

What is the process for enabling audio to start downloading immediately after the user clicks a button on the same webpage?

Can you please set up a function so that when users click on the "Download" button, the audio file automatically downloads? Product Details This beat is a melodic, bouncy, and hard track inspired by Lil Mosey. It is priced between $15-$75, with a master ...

Why won't disabling a Javascript checkbox also grey out the associated label in ASP.NET?

My current challenge involves using JavaScript to disable checkboxes in a checkbox list. The code snippet I am working with looks like this: var objItem = document.getElementById("<%= resCBL.ClientID %>"); var checkBoxes = objItem.getElementsByTagN ...

Is there a way to retrieve the value of a dropped file in a file input using jQuery?

Can the data from a dropped file be set in a file upload input field? Or does a dropped file need to be instantly uploaded to the server? Here is an example code snippet: <input type="file" id="drop-box" /> $("#drop-box").on('drop', fun ...

My toggleclass function seems to be malfunctioning

I am encountering a strange issue with my jQuery script. It seems to work initially when I toggle between classes, but then requires an extra click every time I want to repeat the process. The classes switch as expected at first, but subsequent toggles req ...

Do not use unnecessary variables for storing references in ES6

Despite using react es6, I am still unsure how to refrain from needing to use the variable that for this scenario: const that = this; UploadApi.exec(file).then(data => { that.setState({ loading : false}); }); ...

Conceal the results of echoing json_encode

One dilemma I encountered was passing an array from PHP to JavaScript using json_encode and ajax. The only method that seemed available was to use echo json_encode($var) This approach printed out the contents of $var on the page due to the echo statement ...

Plugin for saving inline edits in CKEditor 4

After creating a plugin for ajax save, I found the documentation confusing when it comes to implementation. How can I make the button responsive and able to save content using AJAX with PHP? Currently, I am unable to retrieve the content. Directory: /plug ...

Are the elements in char *name[] organized as an array of pointers or as a pointer to

Can you clarify the declaration of strings like this for me? char *mypointerorarray[] = {"string1", "string2", "string3"}; Is mypointerorarray a pointer to several arrays or an array of pointers to strings? Additionally, what would be the correct way to ...

developing a side navigation panel with html and jquery

Attempting to incorporate a side menu into my website using HTML, jQuery, and JavaScript. Currently able to display the side menu but struggling with implementing the functionality to open and close it. Seeking assistance with this particular issue. HTML: ...

What causes the variation in size between the next/image and img HTML elements?

Two Images, Different Sizes! https://i.sstatic.net/vpoNG.jpg There seems to be a discrepancy in size between the image rendered by the next/img component and the one displayed using the img element. Interestingly, they both use the same image source and ar ...

What could be causing the jqgrid reload event to not work after using jquery.ajax(type:html)?

:) I am encountering an issue with jqgrid. I have a setup where the main page (referred to as "A") contains one jqgrid, which is a simple grid. Another page (referred to as "B") is called from page "A" using jQuery ajax (dataType: "html"). "B" page con ...

The last ajax call in a Spring application is triggered after the user logs in

Lately, I've been encountering a major issue in my application. Whenever I search for a value in the application and my session has expired, the application correctly redirects me to the login page. However, upon logging back in, instead of being di ...

What is the most effective method for retrieving Key-Value Pairs from a disorganized String?

Avoiding hard-coded rules specific to certain patterns is crucial. I am currently working on a project similar to AWS Textract (link here). I have successfully extracted data from files, albeit in an unstructured manner. Now, my goal is to find the best w ...

The function startAfter() in Firebase Realtime Database (RTDB) does not seem

I'm currently implementing pagination for a list of items using Vuefire, and encountering an error with the following code snippet (the function works properly with startAt() but not with startAfter()) lastVisible is an object within my component&apo ...

Send a nested object as part of the POST request

Is there a way to send a nested object using a POST request? let name = "test", path = "?diffCurr%5B%5D=FALSE&diffProv%5B%5D=FALSE", data = { datatype:"report", "value":{ "name":name, "query":pat ...

Guide on developing and releasing a Vuejs component on NPM

I have been diving deep into vue lately and incorporating it into all of the projects at my workplace. As a result, I have developed various components, particularly autocomplete. Although there are plenty of existing options out there, none seem to fulfil ...

The useReducer state change introduces a slight one-character delay during the onChange event

When utilizing useReducer for state management, I encounter a delay issue with onChange and the reducer resulting in one character lag. There is a useEffect that relies on character changes to toggle the validity value between true and false. Oddly enough ...