What is the process for obtaining the final element in an array of objects when a particular character is present in the value of a key?

Given the following array:

arrOfOranges =
[{ "kerp": "thisThing", "time": "@ rocks 3"},
{ "kerp": "otherThing", "green": "blah"},
{ "kerp": "thisThing", "time": "(countriesToTheStart ^"},
{ "kerp": "anotherThing", "yellow": "row row"},
{ "kerp": "anotherThing", "yellow": "rigorous"},
{ "kerp": "thisThing", "time": ",,,,"}]

Each item in the array has the fixed structure:

[{kerp: ''}] that can be one of three values: thisThing, otherThing, or anotherThing. The second key for each object depends on the value of 'kerp'.

If kerp is 'thisThing', then the second key is 'time'. => { "kerp": "thisThing", "time": ""},

If kerp is 'otherThing', then the second key is 'green'. => { "kerp": "otherThing", "green": ""},

If kerp is 'anotherThing', then the second key is 'yellow'. => { "kerp": "anotherThing", "yellow": ""},

I am trying to extract the last item in the array with 'kerp': 'thisThing'. However, the value associated with the 'time' key must contain a letter.

In the given array, the last item has 'kerp': 'thisThing', but the 'time' does not contain a letter.

Therefore, I need to retrieve the item from arrOfOranges where it's the last item with kerp as thisThing and time containing letters in the value:

{"kerp": "thisThing", "time": "(countriesToTheStart ^"}

Here is my current approach:

if (arrOfOranges.filter(a=>a.kerp === "thisThing")) {
    // Checking if the time value contains any letters
    if(arrOfOranges.time.match(/[\w]+/g))  {
        return arrOfOranges.slice(-1)[0];
    }
}

However, this solution is not working as intended. How can I achieve the desired outcome?

Answer №1

To ensure proper filtering, make sure the check stays within the filter function.

const arrOfOranges = [
  { "kerp": "thisThing", "time": "@ rocks 3"},
  { "kerp": "otherThing", "green": "blah"},
  { "kerp": "thisThing", "time": "(countriesToTheStart ^"},
  { "kerp": "anotherThing", "yellow": "row row"},
  { "kerp": "anotherThing", "yellow": "rigorous"},
  { "kerp": "thisThing", "time": ",,,,"}
 ]

const result = arrOfOranges.filter(orange => orange.kerp === "thisThing" && orange.time.match(/[\w]+/g));

console.log(result);

Answer №2

To reverse the order of your arrOfOranges, you can utilize the .reverse() method and then apply the .find() function on the reversed array. The find method will identify and return the first object for which the provided callback returns true. In the example below, I have set it to return true when the time key contains a word character represented by \w and when the kerp key matches "thisThing". It is important to note that I used .slice() before invoking .reverse() to avoid directly altering the original arrOfOranges array:

const arrOfOranges = [{ "kerp": "thisThing", "time": "@ rocks 3"}, { "kerp": "otherThing", "green": "blah"}, { "kerp": "thisThing", "time": "(countriesToTheStart ^"}, { "kerp": "anotherThing", "yellow": "row row"}, { "kerp": "anotherThing", "yellow": "rigorous"}, { "kerp": "thisThing", "time": ",,,,"];

const search = {kerp: "thisThing", key: "time"};
const res = arrOfOranges.slice().reverse().find(
  obj => obj.kerp === search.kerp && /\w/.test(obj[search.key])
);

console.log(res);

If you prefer a slightly more efficient method, you can opt for a traditional for loop that iterates backwards through the array:

const arrOfOranges = [{ "kerp": "thisThing", "time": "@ rocks 3"}, { "kerp": "otherThing", "green": "blah"}, { "kerp": "thisThing", "time": "(countriesToTheStart ^"}, { "kerp": "anotherThing", "yellow": "row row"}, { "kerp": "anotherThing", "yellow": "rigorous"}, { "kerp": "thisThing", "time": ",,,,"];

const search = {kerp: "thisThing", key: "time"};
function findObj(data, search) {
  for(let i = data.length-1; i >= 0; i--) {
    const curr = data[i];
    if(curr.kerp === search.kerp && /\w/.test(curr[search.key]))
      return curr;
  }
}

console.log(findObj(arrOfOranges, search));

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

Troubleshooting connection timeouts between node.js and amqp

In my project, I am utilizing RabbitMQ through the AMQP module in Node.js with 2 producers and 2 consumers. Here is the code snippet for establishing connections for the consumers: function init_consumers( ) { console.log( 'mq: consumers connect ...

Issue with large date changes causing MUI DatePicker to freeze

The MUI DatePicker, whether from Labs or X, was functioning perfectly. However, I am now facing an issue where it hangs when trying to change the date by ten years. It appears that the code gets stuck in an endless loop, yet there are no errors displayed i ...

What is the best way to design a circular icon using OpenLayers?

I am currently incorporating openlayers into my ionic app and working on placing users on the map. I have encountered a problem as I am unsure how to apply custom CSS styling to the user element, which is not directly present in the HTML. In the screenshot ...

A dynamic input field will appear on the page following the closing </form> tag

I encountered an unusual situation where upon clicking a button with the id #fusk, dynamic elements are added. Here is the code snippet: $('#imgc').append( "<div class='divi'>" + "<input type='hidden' name=' ...

Web Audio API functions are encountering a playback issue on iOS 13.3, despite working smoothly on previous iOS versions

I have been developing an audio visualizer using the web audio API. It was functioning smoothly on PC, however, after upgrading to iOS 13.3, it no longer operates on Apple mobile devices. The root cause of this issue remains a mystery to me. The problem s ...

Tips for preventing JavaScript errors when making cross-domain requests using AJAX

Is there a way to prevent or handle JavaScript errors without causing the script to crash? Error message: No data returned $.ajax({ type : 'GET', dataType : 'jsonp', url : '//cvrapi.dk/api?search=dsfsdfsd&country= ...

Flask - Issue werkzeug.exceptions.BadRequestKeyError -

I've been encountering an issue while trying to run my first Flask app. After sending a POST request on Postman, I keep getting the following error: Error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The server couldn't understand t ...

Refreshing/Redrawing/Resizing a panel in jQuery Layout when toggling the visibility of a header or footer

Currently utilizing a standard jQuery layout with north, south, west, east, and center sections as outlined in the documentation. In both the west and center panels, there are header and footer panes included. While everything is functioning correctly, I ...

Is there a way to refresh a webpage on an express route and display an error message at the same time?

I'm currently in the process of building a basic website that includes features for user login and logout. This functionality is based on a local JSON file containing a list of users and their hashed passwords. My server setup involves using express s ...

What is the best way to differentiate and analyze new AJAX output from previous data using div elements?

Embarking on a project to develop a high/low game using JavaScript, I encountered a perplexing issue where the displayed numbers seemed to be out of sync with the variables stored. This discrepancy left me scratching my head as I struggled to get them to a ...

Processing Jackson JSON deserialization, extracting root element directly from the JSON data

I am struggling with a query related to Jackson which seems like it should have a simple solution, but I can't figure it out. So here's the deal: I have a Java POJO class that goes something like this (with getters and setters) @JsonRootName(va ...

show button after the page has finished loading

I have a button similar to this: <input type="submit" id="product_197_submit_button" class="wpsc_buy_button" name="Buy" value="Add To Cart"> However, I am encountering an issue where if the user clicks the button before all scripts are loaded, an e ...

Tips on using MUI Texfield and Redux to update state

I am facing an issue with my input field as I attempt to pass some information before navigating to a different page. The problem lies in the fact that my Redux state is not updating, although the console confirms that the value is being passed correctly. ...

Parsing JSON data from numerous gigabyte-sized .txt files and appending them all to a single list

I am facing a challenge with processing 300 txt files, each ranging from 80-100mb in size. I attempted to load all the content into a list object simultaneously, but encountered a recurring MemoryError issue whenever I tried to process more than 3 files at ...

I encounter internal server errors when trying to upload images in React

Attempting to send a post request with an image, but encountering errors without understanding why. const [image, setImage] = useState([]); const handleImage = (event) => { setImage(...Array(event.target.files[0])) } const handleSubmit ...

Is it possible to dynamically choose between GET and POST methods for an AJAX request?

Consider the following code snippet which intercepts the form submission event from two different forms. $("#aaa, #bbb").submit(function(e) { e.preventDefault(); var form = $(this); var url = form.attr('action'); $.ajax({ ...

Javascript loops through a map that contains other maps

At first, I set up the layout like this: <ul id="state_${abbr}"></ul> on the jsp page and now I have to load this JSON map of maps to the layout. coverage.phone.data = { "CA" : { "LOS ANGELES" : "1111", "TORRANCE" : "2222", "S ...

When using Multer for file upload, the req.body returns as an empty object while req.file is undefined

I previously shared a problem I encountered while using multer for file upload in the MERN stack. Despite my attempts, I have not yet been able to resolve it. In my app, I am using both body-parser and multer. Here is the order of code in my index.js file: ...

Combine PHP, jQuery, and AJAX to retrieve multiple values simultaneously

I have been using jQuery AJAX for my projects. When I make an AJAX call to a PHP page, it normally returns a single value to the success function of AJAX. However, I am now looking to retrieve multiple data individually. How can I achieve this? This is th ...

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...