Find the index of the final empty element in an array using AngularJS

var caseOne = [
    {"name":"Felicity", "gender":"F", ...   ... ,"type":"Admin"},
    {"name":"Tony", "gender":"M", ...   ... ,"type":""},
    .
    .
    .
    .
    {"name":"Super Man", "gender":"M", ...   ... ,"type":""},
    {"name":"Wonder Women", "gender":"F", ...   ... ,"type":""},
    {"name":"Hulk", "gender":"M", ...   ... ,"type":"User"},
    {"name":"Loky", "gender":"M", ...   ... ,"type":"User"},
    {"name":"Thore", "gender":"M", ...   ... ,"type":"Admin"}
];

var caseTwo = [
    {"name":"Felicity", "gender":"F", ...   ... ,"type":"Admin"},
    {"name":"Tony", "gender":"M", ...   ... ,"type":""},
    .
    .
    .
    .
    {"name":"Super Man", "gender":"M", ...   ... ,"type":""},
    {"name":"Wonder Women", "gender":"F", ...   ... ,"type":""},
    {"name":"Hulk", "gender":"M", ...   ... ,"type":"User"},
    {"name":"Loky", "gender":"M", ...   ... ,"type":"User"},
    {"name":"Thore", "gender":"M", ...   ... ,"type":"Admin"},
    {"name":"Bat man", "gender":"M", ...   ... ,"type":""}
];

I have an array structure similar to the above examples. I am looking for assistance in extracting all records that appear after the last occurrence of "type":"". In this scenario, it should return the last 3 records from caseOne and 0 records from caseTwo, which essentially means all records after "type":"".

Your help is greatly appreciated.

Desired output

caseOne = [
    {"name":"Hulk", "gender":"M", ...   ... ,"type":"User"},
    {"name":"Loky", "gender":"M", ...   ... ,"type":"User"},
    {"name":"Thore", "gender":"M", ...   ... ,"type":"Admin"}
];

caseTwo = [];

Answer №1

Create a function called getEndIndex() that can be used to find the index of the last object in an array with a specific type: "". Using this index, you can then use the splice() method to extract the desired output.

var caseOne = [
    {"name":"Felicity", "gender":"F","type":"Admin"},
    {"name":"Tony", "gender":"M","type":""},
    {"name":"Super Man", "gender":"M","type":""},
    {"name":"Wonder Women", "gender":"F","type":""},
    {"name":"Hulk", "gender":"M","type":"User"},
    {"name":"Loky", "gender":"M","type":"User"},
    {"name":"Thore", "gender":"M","type":"Admin"}
];

var caseTwo = [
    {"name":"Felicity", "gender":"F","type":"Admin"},
    {"name":"Tony", "gender":"M","type":""},
    {"name":"Super Man", "gender":"M","type":""},
    {"name":"Wonder Women", "gender":"F","type":""},
    {"name":"Hulk", "gender":"M","type":"User"},
    {"name":"Loky", "gender":"M","type":"User"},
    {"name":"Thore", "gender":"M","type":"Admin"},
    {"name":"Bat man", "gender":"M","type":""}
];

function getEndIndex(caseArray){
  var endIndex;
  caseArray.forEach(function(obj, index){
    if(obj.type === ''){
      endIndex = index;
    }
  });
  return endIndex;
}

var index = getEndIndex(caseOne);
var resultCaseOne = caseOne.splice(index+1, caseOne.length);
console.log('-----caseOne-----');
console.log(resultCaseOne);

index = getEndIndex(caseTwo);
var resultCaseTwo = caseTwo.splice(index+1, caseTwo.length);
console.log('-----caseTwo-----');
console.log(resultCaseTwo);

Alternatively, if your array is likely to have objects with type:'' at the end, you can search for the index starting from the last object in the array like this:

var caseOne = [
    {"name":"Felicity", "gender":"F","type":"Admin"},
    {"name":"Tony", "gender":"M","type":""},
    {"name":"Super Man", "gender":"M","type":""},
    {"name":"Wonder Women", "gender":"F","type":""},
    {"name":"Hulk", "gender":"M","type":"User"},
    {"name":"Loky", "gender":"M","type":"User"},
    {"name":"Thore", "gender":"M","type":"Admin"}
];

var caseTwo = [
    {"name":"Felicity", "gender":"F","type":"Admin"},
    {"name":"Tony", "gender":"M","type":""},
    {"name":"Super Man", "gender":"M","type":""},
    {"name":"Wonder Women", "gender":"F","type":""},
    {"name":"Hulk", "gender":"M","type":"User"},
    {"name":"Loky", "gender":"M","type":"User"},
    {"name":"Thore", "gender":"M","type":"Admin"},
    {"name":"Bat man", "gender":"M","type":""}
];

function getEndIndex(caseArray){
  var i;
  for(i=caseArray.length-1; i>=0; i--){
   if(caseArray[i].type === ''){
      break;
    }
  }
  return i;
}

var index = getEndIndex(caseOne);
var resultCaseOne = caseOne.splice(index+1, caseOne.length);
console.log('-----caseOne-----');
console.log(resultCaseOne);

index = getEndIndex(caseTwo);
var resultCaseTwo = caseTwo.splice(index+1, caseTwo.length);
console.log('-----caseTwo-----');
console.log(resultCaseTwo);

Answer №2

How can retrieving array elements in this manner be beneficial? Instead of manually searching through an array for elements after a specific point, there may be a more efficient solution available. In any case, you are seeking code similar to:

// original data
const data = [
    {"name":"Felicity", "gender":"F", "type":"Admin"},
    {"name":"Tony", "gender":"M", "type":""},
    {"name":"Super Man", "gender":"M", "type":""},
    {"name":"Wonder Women", "gender":"F", "type":""},
    {"name":"Hulk", "gender":"M", "type":"User"},
    {"name":"Loky", "gender":"M", "type":"User"},
    {"name":"Thore", "gender":"M", "type":"Admin"}
];
const index = Array
.from( data ) // Create a copy of the array to avoid altering the original when reversing.
.reverse() // Reverse the array so findIndex can be used instead of implementing findLastIndex.
.findIndex( entry => !entry.type ); // Determine the index of the first element without a type value.
const resultData = data.slice( data.length - index, data.length ); // Extract a portion of the original array.
console.log( resultData );

Answer №3

To achieve this, you can follow these steps:
   
   let exampleArray = [
                    {"name":"Alice", "gender":"F","type":"Admin"},
                    {"name":"Bob", "gender":"M","type":""},
                    {"name":"Super Woman", "gender":"F","type":""},
                    {"name":"Spider Man", "gender":"M","type":""},
                    {"name":"Iron Man", "gender":"M","type":"User"},
                    {"name":"Black Widow", "gender":"F","type":"User"},
                    {"name":"Deadpool", "gender":"M","type":"Admin"}
                ];
                
                let modifiedArray = [];
                let indexCount = 0;
                
                for(let i=0; i<exampleArray.length; i++) {
                    if(exampleArray[i].type == ''){
                        indexCount++;
                    }
                }
                
                modifiedArray = exampleArray.splice(indexCount+1, exampleArray.length);
            console.log(modifiedArray);

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

Unending cycle of jQuery focus() event within a <select> element

This is the HTML code I am working with: <select id="select-one"> <option value="">Choose</option> <option value="1">House</option> </select> <select id="select-two"> <option value="">Choose< ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...

Is it possible to prevent the fade out of the image when hovering over the text after hovering over the div or image, causing the text to fade in?

Using React and CSS. I have set up my application to display a faded image on hover, with text that fades in over it. However, I am facing an issue where touching the text with my cursor removes the fade effect. Does anyone have a solution for preventing ...

Content Security Policy in Firefox Extension blocking local DataTables js

After downloading the js for DataTables, I attempted to load it onto my Firefox extension but encountered a Content Security Policy block: Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src moz-ext ...

React Native - Listview triggering multiple refreshes when pulled down

As I attempt to implement the onScroll function for ListView to detect when a user has pulled the list down beyond a certain pixel value in order to trigger an AJAX call and refresh the list, I am facing an issue where it fires multiple times leading to a ...

Issue with arrow functions in Reactjs Material-UI - Unexpected token error

I am currently trying to integrate components from material-ui into a project based on react-rocket-boilerplate. An error message is appearing: [23:55:11] gulp-notify: [Compile Error] C:/react-rocket-boilerplate/app/js/components/Sidebar.js: Unexpected ...

Angularjs directive retrieves infowindow DOM element from Google Maps

In order to apply some style fixes to the Infowindow, I am trying to select the element with the class 'gm-style-iw'. This selection process is taking place within an angularjs directive. <div ui-view="full-map" id="full-map" class="mainMap c ...

Extracting image dimensions using JavaScript - a simple guide

Having created a test for an upcoming project, I have encountered a problem that I am struggling to resolve. Despite my efforts to search the internet for a solution, I have been unable to find one due to: My limited understanding of Javascript The code l ...

Challenges arise with the height settings of ui-grid

Currently, I am facing an issue with using height: auto on an angularJS ui-grid. The problem arises from an inline style that specifies a fixed height on the div to which the ui-grid attribute is added. Additionally, the function getViewPortStyle() dynamic ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

Including the Advanced Custom Fields (ACF) PHP value into a JavaScript array within a foreach loop

I am currently working with a code snippet that involves the variable $v. Each $v holds a specific string value (ex: icon1, icon2, icon3, icon4): <script type="text/javascript"> var vArr = new array(); </script> ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

Importing events from the calendar causes disarray in other data columns when sorted by date

I have a unique code that successfully imports my shared Google Calendar into a spreadsheet. In my medical office, I manage all appointments through a master Calendar. The calendar data includes start time, location, description, and title in columns B, ...

Scheduled tasks arranged by the user

My goal is to empower my users to schedule specific actions at their preferred times. With a node server hosted on Azure, I am exploring the potential of using node-schedule for this functionality. One idea I'm considering is running a master schedule ...

displaying HTML content in an Angular controller

Can someone please guide me in the right direction? I am working on a web app where users need to click a button as quickly as possible to get a score. The design requires that this score be displayed in double digits, for example, 9 would be displayed as ...

Can Ionic iOS apps integrate databases?

Currently working on an Ionic app for iOS and feeling unsure about the best approach to implement the model. I need to read and save data, with offline functionality being a key requirement. Does anyone have any suggestions? I've heard that Firebase ...

Is there a way to create an input mask that looks similar to this format --:--:--?

Is there a way to format an input in React to accept numbers in the format --:--:-- as 99:99:99 without using any plugins? Unfortunately, I am not sure how to achieve this with a simple input field. However, here is a snippet of code that I tried: <Tex ...

Using the useQuery() function in a Next.js React app successfully fetches data from the API on the client side, yet the same API call fails to work when implemented in getServerSideProps on

I am attempting to retrieve data from the backend server using React Query within Next JS getServerSideProps. Here is the function used to fetch the data: export const getGoogleAuthUrl = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC ...

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

Experiment with Jasmine to evaluate Angular's $valid and $pristine statuses

I am facing an issue with my Jasmine test as it does not seem to be accepting the use of $pristine and $valid within my controller. The error message that is being displayed states: TypeError: 'scope[...].$pristine' is null or not an object T ...