Keep the final item in an array that shares the same attribute

I am working with an array

const obj=[{fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 5, smu: 3, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 7, smu: 3, stowage: 5, index: "FC-093"/}
 ]

In my code, I need to keep the last object in the array which has the same property 'index' as the previous one. In this case, objects with index 'FC-093' should be removed, resulting in:

[{fullCart: 5, halfCart: 7, smu: 3, stowage: 5, index: "FC-093/"}]

Answer №1

Here is the solution you've been looking for.

  1. To extract every unique index value from an array, utilize the .map() method
  2. Iterate through the unique array and employ the findLast method to retrieve the last element in the object array based on each value in the unique array, then add it to the result array

const obj=[
 {fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 5, smu: 3, stowage: 5, index: "FC-093"},
 {fullCart: 10, halfCart: 7, smu: 3, stowage: 5, index: "FC-093"},
 {fullCart: 3, halfCart: 6, smu: 4, stowage: 5, index: "FC-095"},
 {fullCart: 3, halfCart: 6, smu: 5, stowage: 5, index: "FC-095"},
 {fullCart: 10, halfCart: 7, smu: 8, stowage: 5, index: "FC-095"},
 {fullCart: 2, halfCart: 8, smu: 10, stowage: 5, index: "FC-098"},
 {fullCart: 10, halfCart: 9, smu: 2, stowage: 5, index: "FC-098"}
];
let result = [];//initialize result array

//generate a unique array
const unique = [...new Set(obj.map(item => item.index))];
console.log(unique)//prints every unique value from key index found in an array 

//iterate through unique array
unique.forEach(ele => {
  //retrieve the last element with matching index value in the unique array
  let res = obj.findLast((element) => element.index == ele);
  result.push(res)
})

console.log(result)//expected output

Answer №2

Using this code snippet, you can iterate through all elements and retain only the last element with a specific id.

let finalResult = Object.values(objects.reduce((accumulator, element) => {
  accumulator[element.identifier] = element;
  return accumulator;
}, {}));

Answer №3

It seems like there might be some confusion regarding your query. If you're looking to retrieve the last element, you can achieve that with the following code snippet:


    function getLastElement(arr) {
        let lastIndex = arr.length - 1;
        return arr[lastIndex];
    }

Alternatively, if you want to eliminate the last element from the array, you can create a new array and assign it to the existing one like this:


let originalArray = [0, 1, 2, 3, 4, 5]

function createNewArray(arr) {
    return arr.slice(0, -1);
}

originalArray = createNewArray(originalArray);
// originalArray now holds [0, 1, 2, 3, 4]

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

When considering the real-time retrieval of millions of objects, would it be more efficient to store them in an array or utilize a database such as Redis?

In my current project, I am creating a complex simulation where numerous entities have the ability to interact with one another. Currently, all of these entities are being stored in a standard list structure. Would it be more efficient to utilize a datab ...

Manipulate sibling elements using jQuery's addClass and remove methods

I have implemented a function that adds the class active to elements when they reach the top of the browser, ensuring that the next element will scroll in over the top. While this works smoothly in Chrome, I am encountering some jumping behavior when testi ...

The Google Docs viewer is displaying an empty screen

I have been utilizing the Google Docs viewer on my website: <div class="embed-r embed-responsive-a"> <iframe class="embed-responsive-it" src="https://docs.google.com/viewer?embedded=true&amp;url=http://LINK.PDF"></iframe> </div& ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

Retrieving data from varied React components - triggered by clicking a LOG button

function Copy() { const Message = "MESSAGE"; const [messageList, setMessageList] = useState([{ text: "Hello", id: 1 }]); const [newMessageValue, setNewMessageValue] = useState(0); const addToMessageList = () => { alert(n ...

I'm so confused about the operation of each method in this context

I am experimenting with a simple process involving setTimeout function. My goal is to make the letters of a name appear individually and gradually at different times. For example, if the name is NAZ, I want the letters to appear in this order: first N, the ...

There seems to be an issue with the post request to a PHP file as it is returning a null value when

I have been struggling with this issue for a while now and can't seem to understand why I keep getting null after calling my $.ajax function. I pass an associative array containing the method name, then invoke the method in PHP to return a JSON string ...

Configuring Angular to use ES6 syntax

Trying to integrate angular google maps with es6 syntax has been a challenge for me. In es5, the code typically looks like this: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key&ap ...

React component's useEffect runs twice when missing dependencies

Hi there, I'm currently facing an issue with the useEffect hook in my code. I have set it without any dependencies because I only want it to run once. The problem arises when the useEffect in the Profiles.js component runs twice, even though I am usin ...

After applying styling, the modal close button refuses to be clicked

I'm currently facing an issue where I am trying to enhance a modal window with a close button, but encounter problems once styling is applied. The unique aspect of this problem arises from the fact that the close button is not directly in the page HTM ...

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

The JavaScript function's if and else statements are being executed simultaneously

Upon loading the page, I am checking the value of a dropdown. Strangely, when I debug, it appears that the controller is executing both the if and else statements, which should not be happening. /* Here is my code: */ $(window).load(function() { ...

When I include scroll-snap-type: y; in the body tag, the scroll-snapping feature does not function properly

Hey there! I've been trying to implement scroll-snapping on my project but unfortunately, I couldn't get it to work. I tested it out on both Chrome and Firefox, but no luck so far. Here's the code snippet I've been working with, would a ...

Checking if a variable is true with jQuery

Check out this snippet of code: <main class="ok">My text</main> <script> $(document).ready(function() { if ( $('body').not('main.ok') ) { // or if ( Boolean ( $('main.ok') ) == false ) { ...

Tips on using Visual Studio Code to troubleshoot Angular 4 unit tests

I am working on an Angular 4 project with Material design in Visual Studio Code. The setup is done using angular/cli. Currently, I have been writing unit tests using Karma and Jasmine. However, when trying to debug the tests by setting breakpoints, it doe ...

Vue-powered carousel having trouble rotating properly

I recently came across a carousel created using vanilla javascript and html. I attempted to convert it to Vue, but encountered some challenges. The carousel is supposed to dynamically pull images from a SharePoint list. However, in my version, the images a ...

Struggling with implementing ng-repeat in AngularJS for displaying HTML content

I stumbled upon a post that covers pretty much what I'm trying to achieve: AngularJS - Is it possible to use ng-repeat to render HTML values? Currently, the code appears like this and displays correctly as text: <div ng-repeat="item in items.Item ...

Tips for revealing a position: absolute div that is currently hidden with display: none styling

Below is the code for a div element that I want to temporarily hide using JavaScript: <div id="mydiv" style="position: absolute; top: 60px; left:5px; right:25px; bottom:10px;"> </div> After hiding it with display:none in my ...

I'm new to this, but can someone explain why I'm being redirected to the register_db.php page when I click on the register button?

Why when I click the register button, it redirects me to the register_db.php page instead of sending the data to the database and keeping me on the same register.php page? I want the data to be sent to the database without changing the webpage. register.p ...

Interactive Show Map with Autocompletion Feature

I attempted to implement autocompletion for my application and integrate it with Google Maps, but I'm encountering issues. The code for autocompletion is located in a separate JavaScript file called autocomplete.js. Since I already have a Google Map ...