Locating a specific item by referencing its neighboring sibling

Imagine having a dataset structured like this:

var items = [
  {
    category: 'shoes',
  },
  {
    category: 'hat',
  },
  {
    category: 'scarf'
  },
  {
    category: 'shoes'
  }
]

I am in search of a method to locate (find item) and transform (edit item on-the-fly) the item with a matching category of shoes where the node before it has a category that equals scarf. Essentially, only the last item in the array should be targeted.

Is there a JavaScript solution for achieving this task? Are there any libraries that offer this specific functionality?

Answer №1

A straightforward solution could be achieved using a for loop:

for (let index = 0; index < elements.length - 1; index++) {
  if (elements[index + 1].category == "top" && elements[index].category == "bottom") {
    // perform necessary actions here
  }
}

Answer №2

here's a sample function utilizing the reduce method:

var items = [
  {
    category: 'shoes'
  },
  {
    category: 'hats'
  },
  {
    category: 'gloves'
  },
  {
    category: 'shoes'
  }
]
function filterItems(arr,item,before){
  return arr.reduce(function(acc,current,index,arr){
        if(current.category==item && arr[index - 1] && arr[index-1].category==before){
         acc.push(current); 
        }
        return acc ;
    },[])
}
console.log( filterItems(items,'shoes','gloves'))

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

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

Having trouble showing JSON data with Ionic 2 and Xcode?

Extracting JSON data from a JSON file in my project and viewing it using "ionic serve" on my Mac has been successful. However, I am facing an issue after building for IOS in XCode. I import the generated project into XCode as usual, but the JSON data is no ...

Using WEBGL to Showcase Your Images: A Step-by-Step Guide

I'm hoping to effortlessly showcase an image on the canvas at specific x and y co-ordinates using WEBGL, but I'm unsure of the process. Must shaders be included along with all other technical details? I've come across code snippets for displ ...

Generate a new perspective by incorporating two distinct arrays

I have two arrays containing class information. The first array includes classId and className: classes = [ {classid : 1 , classname:"class1"},{classid : 2 , classname:"class2"},{classid : 3 , classname:"class3"}] The secon ...

Is there a clever method for saving the latest section of an uninterrupted flow in an array?

I'm facing the challenge of managing a constant flow of data in my programming project. I want to create a fixed-size buffer array that only retains the most recent T observations from this data stream. However, I'm struggling to devise an effici ...

Unable to Interpret JSON in Universal Windows Platform

I developed a UWP application that parses data to JSON format. The JSON data can be found here. However, I am facing issues with parsing the "jawaban" section of the JSON data which is causing an error message to appear like this: https://i.stack.imgur.co ...

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

Enumeration field with Conditional logic

I am currently developing a Content Management System (CMS) using strapi for a client, and I want to provide them with the ability to control the questions included in a questionnaire. Each question will be categorized under different sections in the quest ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

Encountered a null pointer exception while trying to send an array from Java to an Android device using ObjectInputStream and

I've been facing an issue with passing an array into a list view using ObjectOutput/InputStream. Everything works perfectly up to the point where I try to insert the array into the view - I encounter a nullpointerexception. Interestingly, I have no pr ...

Ensure that ExpressJS response includes asynchronous try/catch handling for any errors thrown

Currently working with ExpressJS version 4.16.0, NodeJS version 10.15.0, along with KnexJS/Bookshelf, and encountering issues with error handling. While errors are successfully caught within my application, the problem arises when trying to retrieve the e ...

"Embrace the Tempus Dominus integration for the latest version of Bootstrap -

After reading through the script documentation, I attempted to implement it on my example page. However, I keep encountering the error: Uncaught TypeError: $(...).datetimepicker is not a function. Here's the code snippet that I included in the head s ...

Struggling to import PHP array data into MySQL database

Hey there! I've got this array called $name[] that I've been trying to insert into the second field of my table, but for some reason it's not working properly. The table just stays completely blank and I can't figure out what is wrong w ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

Using NodeJS to facilitate communication between multiple NodeJS instances while also overseeing operations of a Minecraft server

I have a question about communicating between NodeJS instances. Let's say I have one NodeJS instance running a chat room - how can I access that chat and see who is connected from another NodeJS instance? Additionally, I'm curious if it's f ...

Is there a tool available that can convert a cron schedule into a more user-friendly, easy-to-read format?

My search for an NPM package that can handle this task has been fruitless so far. I am in need of a cron library that can convert a monthly cron job into easily readable text. For example, inputting 0 0 14 * * should output "Monthly", rather than the curre ...

Exploring the process of adding arrays to highcharts using jQuery

All my coding work has been carried out on FIDDLE I have carefully monitored all the arrays: MARKET[0], MARKET[1], MARKET[2], MARKET[3], MARKET[4], MARKET[5], MARKET[6], MARKET[7]. They display correctly in alerts. However, when I attempted to incorporate ...

Issue encountered with Quik Flip plugin in jQuery

I am currently experiencing an issue with a jQuery plugin known as quikflip. This plugin is designed to flip an image using a flipping effect, similar to turning cards. My goal is to use it to flip a list of images representing cards; I have a total of 20 ...

Retrieve the Axios response without interruption, even in the event of an exception, when making API calls with multiple files

Currently, as a beginner diving into Vue.js, I am exploring the world of frontend development by integrating Vue with my Laravel backend. To streamline my API calls and make them more organized for different models, I decided to create a separate file name ...

Javascript closures: a common pitfall

I'm facing an issue with my code where it is not behaving as expected. Although I believe the code itself is correct, there seems to be a problem that I'm unable to identify. The goal of the code is to display numbers 10 through 0 with a 2-second ...