Discover the initial two instances of a specific element within a collection of javascript objects

Within my javascript arraylist, I am currently storing the following elements:

list = [
 {header: "header1", code: ""},
 {label: "label1", price: 10},
 {header: "header2", code: ""},
 {header: "header3", code: ""},
 {header: "header4", code: ""}
]

My question is how can I filter the array to retrieve only the first 2 occurrences of the element "header"?

The expected output would be:

list = [
 {header: "header1", code: ""},
 {label: "label1", price: 10},
 {header: "header2", code: ""}
]

I'm looking for a feasible and efficient solution to achieve this using javascript.

Answer №1

To extract non-header items from the array, you can filter it based on the count parameter. If a header item is encountered, decrement the count.

const
    topHeaders = (array, count = 2) =>
        array.filter(({ header }) => count && (!header || count--));

console.log(topHeaders([]));
console.log(topHeaders([{ header: "header1" }]));
// Other test cases...
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Here is a custom solution just for you.

let count = 0;
const searchKey = 'header';
const resultList = [];
for(let index=0; index<list.length; index++)
{
    const object = list[index];
    for(const property in object)
    {
        if(property === searchKey)
        {
            resultList.push(object);
            count++;
        }
    }
    if(count === 2)
    {
        break;
    }
}

Your desired output will be stored in resultList.

Answer №3

Your code is presented below:

 var list = [{header: "header1", code: ""}, {label: "label1", price: 10}, {header: "header2", code: ""}, {header: "header3", code: ""}, {header: "header4", code: ""}];

     var j = 0;
     list = list.filter((ar, i) => {
 if(ar.hasOwnProperty('header') && j < 2){
j++;       
return ar;
     }
     });

     console.log(list);

Answer №4

To simplify the process, filter the list and extract the first two elements as shown below.

const  list = [
 {header: "header1", code: ""},
 {label: "label1", price: 10},
 {header: "header2", code: ""},
 {header: "header3", code: ""},
 {header: "header4", code: ""}
];

const headersArray = list.filter((item) =>
  item.header
).slice(0, 2);


console.log("The extracted headers are ", headersArray)

Answer №5

In this code snippet, I am adding objects to a new array one by one while keeping track of the number of objects with a header. If the count of objects with a header reaches 2, the process stops.

const list = [
 {header: "header1", code: ""},
 {label: "label1", price: 10},
 {header: "header2", code: ""},
 {header: "header3", code: ""},
 {header: "header4", code: ""}
], maxHeader = 2
let result = [], headCounter = 0
list.forEach(item => {
  if (headCounter < maxHeader){
    if (item.header) headCounter++
    result.push(item)
  }
})
console.log(result)

Answer №6

Applying Reduce method :

list.reduce(function (accumulator, currentValue) {

if(accumulator.length < 3 && currentValue.hasOwnProperty('title')){
  accumulator.push(currentValue);
}
 return accumulator;
}, []);

Answer №7

The following code snippet is tailored for your specific scenario.

const items = [
    {title: "Item 1", quantity: 2, price: 10},
    {title: "Item 2", quantity: 1, price: 20}
]

let totalItems = 0
let totalPrice = 0

items.map(item => {
    if(item["quantity"]){
        totalItems += item.quantity;
    }
    
    if(item["price"]){
        totalPrice += (item.quantity * item.price);
    }
})

console.log("Total items: ", totalItems)
console.log("Total price: $", totalPrice)

Answer №8

const newArray = [];
let counter = 0;
for(let index = 0, length = data.length; index < length; index++) {
    if(counter >= 2){
        break
    }
    data[index]['header'] ? counter++ : '';
    newArray.push(data[index]);
}

console.log(newArray);

I trust this aids you in your endeavors!

Answer №9

Here are the steps to achieve this:

  1. Utilize the filter() method to extract all elements with the property header
  2. Apply the findIndex() function on the array list to locate the desired element 2.
  3. Use the slice() method to obtain a portion of the array starting from the initial header until the required header, determined by passing the index discovered through findIndex to the slice()

const list = [
 {header: "header1", code: ""},
 {label: "label1", price: 10},
 {header: "header2", code: ""},
 {header: "header3", code: ""},
 {header: "header4", code: ""}
]

const getItems = (arr,num) => list.slice(0,arr.findIndex(a => a === arr.filter(x => x.hasOwnProperty('header'))[num-1])+1)

console.log(getItems(list,2));
console.log(getItems([ {header: "header1", code: ""}, {header: "header2", code: ""}],2));

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

Learn the steps to retrieve a user's profile picture using the Microsoft Graph API and showcase it in a React application

I'm currently working on accessing the user's profile picture through Microsoft's Graph API. The code snippet below demonstrates how I am trying to obtain the profile image: export async function fetchProfilePhoto() { const accessToken = a ...

Searching for root words in elasticsearch

After successfully implementing stemming for elasticsearch, I noticed that my searches for "code" also bring up results for "codes" and "coding," which is great. However, I encountered a problem when using the "must_not" field in my queries. Including "co ...

Is there a way to reset the dynamic flexslider when a click event occurs?

Seeking a way to refresh the flexslider on a click event. I have embedded the flexslider in a Bootstrap pop-up and need it to update when the user clicks. The issue arises when I try to refresh the slider as it fails to display properly, likely due to losi ...

How can I determine the data type of an Array element contained within an Interface member?

Is there a way to extract the type of key3 in MyInterface2 and use it in key3Value, similar to key2Value? interface MyInterface { key1: { key2: string } } const key2Value: MyInterface['key1']['key2'] = 'Hi' / ...

The order in which JavaScript files are loaded is critical, especially when dealing with external

After experiencing issues with my script not working because it was loaded before jQuery by the client (a necessity), I am seeking a solution. My challenge lies in ensuring that my code waits for jQuery to load before execution, especially when dealing wi ...

Converting JSON objects into datetime: A step-by-step guide

I am looking for a way to display JSON data in a Kendo chart. Below is the code I have: <head> <meta charset="utf-8"/> <title>Kendo UI Snippet</title> <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019 ...

Recursive routing in NodeJS using Express

Certain website APIs have the capability to perform actions such as: Initial user's id their first friend, also a user v v GET /api/users/54282/friends/0/friends/0 ...

How to assign keys and values to array elements in PHP

Trying to accomplish a simple task of adding a key and value to each index of an array. Example array: [0] => Array ( [student_id] => 1 [class_id] => 1 [student_grno] => 11198 [student ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

Tips for resuming a video playback in HTML5 after pausing it for a brief moment

I am working with a video called introVid, and my goal is for it to pause for 2 seconds when it reaches the 1 second mark before resuming playback. Although I've attempted to achieve this using the code below, the video remains in a paused state after ...

Guide to importing multiple controllers using express

For my upcoming full stack project, I am working on various controllers like signup, login, and profile. Instead of manually requiring each controller and adding them to the app using individual lines of code, I am seeking a more efficient solution. I env ...

Utilizing Async / Await in the created lifecycle hook - Vue2

I recently installed the vue-element-loading package and added its component to my page.vue: <vue-element-loading :active="isActive" :is-full-screen="true"/> After adding a variable to my data: data () { return { isActive: false, } } I th ...

Complete the dynamic form submission in a non-blocking manner

My goal is to dynamically add text fields with the click of a button I also aim to extract data from these text fields and insert it into the database Currently, all functions work smoothly, I just need this additional feature. Per ...

Is there a way to randomly change the colors of divs for a variable amount of time?

I have a unique idea for creating a dynamic four-square box that changes colors at random every time a button is clicked. The twist is, I want the colors to cycle randomly for up to 5 seconds before 3 out of 4 squares turn black and one square stops on a r ...

Tips for converting the Instagram cURL post request to a JavaScript request

I am attempting to convert the code I received from Instagram into a token. The code provided in the Instagram DOCS uses a curl request, but I would like to implement it using JavaScript instead. Here is how the original code looks: curl -X POST &bsol ...

How can I efficiently update child states within a parent class using ReactJS?

Exploring the parent component class Root extends React.Component { constructor(props) { super(props); this.state = { word: Words, }; } c ...

The pagination in Laravel Vue is causing a validation error due to an invalid prop type check failing

Recently, I delved into working with Nuxt.js and decided to install the Laravel-Vue-Pagination plugin. However, I encountered an error message in my console system that reads: [Vue warn]: Invalid prop: type check failed for prop "data". Expected Object, ...

What are some alternative ways to link a local MongoDB database to my Android Studio application instead of using MongoLab?

Can someone please help me figure out how to connect my Android Studio project to a MongoDB database stored locally on my PC? I've been searching for solutions that don't involve using MLab, but I haven't had any luck. I've attempted f ...

The functionality of HTML5 canvas image objects is not functioning as expected

I have been working on a function to retrieve an image object using HTML5 canvas, but I keep encountering an error alert (onerror event) function FetchImage() { var img = new Image(); img.src = "http://localhost/assets/images/loadedsprite.png"; ...

What's the best way to update the value of an angular field upon submission?

Could someone please provide instructions on how to update the myName variable when the "submit" button is pressed? Thank you! app.js: app.controller('SomeController', ['$scope', 'emails', function($scope, emails) { emails ...