Changing an item in a refined list

Here is an array written in Typescript:

[ 
  { "size": "100.34 KB", "name": "Phone.jpg", "documentoContentType": "image/jpeg", "type": "object" }, 
  { "size": "606.34 KB", "name": "Tulips.jpg", "documentoContentType": "image/jpeg", "type": "flower" }, 
  { "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" }, ... 
]

The rule for this array is that you can only have one element of each type, meaning there won't be duplicates of a certain type such as "animal".

I am looking to replace the entry "Tulips.jpg" with a new element called "Cactus.jpg" while keeping the other elements intact:

[ 
  { "size": "100.34 KB", "name": "Phone.jpg", "documentoContentType": "image/jpeg", "type": "object" }, 
  { "size": "900.00 KB", "name": "Cactus.jpg", "documentoContentType": "image/jpeg", "type": "flower" }, 
  { "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" }, ... 
]

I attempted filtering the array to select only the "flower" type and then replacing it with the new element using splice. However, this method didn't work as expected. How can I achieve this?

let newElement = {
    "size": "900.00 KB",
    "name": "Cactus.jpg",
    "documentoContentType": "image/jpeg",
    "type": "flower"
  }

  let array = [ 
  { "size": "100.34 KB", "name": "Phone.jpg", "documentoContentType": "image/jpeg", "type": "object" }, 
  { "size": "606.34 KB", "name": "Tulips.jpg", "documentoContentType": "image/jpeg", "type": "flower" }, 
  { "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" }
]
console.log(array
  .filter(item => item.type === "flower")
  .splice(0, array.length, newElement)
)
console.log(array)

Answer №1

Locate the index of the element returned by the filter function, then remove and replace that element

const replacement = { "size": "900.00 KB", "name": "Cactus.jpg", "documentoContentType": "image/jpeg", "type": "flower" }; 
let array = [ 
  { "size": "100.34 KB", "name": "Phone.jpg", "documentoContentType": "image/jpeg", "type": "object" }, 
  { "size": "606.34 KB", "name": "Tulips.jpg", "documentoContentType": "image/jpeg", "type": "flower" }, 
  { "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" }  
];

let filteredArray = array.filter(item => item.type === "flower")
var index = array.indexOf(filteredArray[0])
array.splice(index, 1, replacement);
console.log(array)

Answer №2

I prefer utilizing a Map over an Array

// converting array into map
const optionsByType = [{ type: 'flower'}, [{ type: 'animal'}]].reduce((map, opt) => {
 map.set(opt.type, opt);
 return map;
}, new Map());

// updating the entry for flower key
optionsByType.set('flower', { type: 'flower', "name": "Cactus.jpg" })

Answer №3

The .filter method will sort through the array based on a specified condition and return a new array without the filtered elements.

You can utilize the.map method to modify the property of matching elements and return the updated element.

arr = [  
     { "size": "606.34 KB", "name": "Tulips.jpg", "documentoContentType": "image/jpeg", "type": "flower" }, 
     { "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" } 
];

let newItem = { "size": "900.00 KB", "name": "Cactus.jpg", "documentoContentType": "image/jpeg", "type": "flower" }

arr = arr.map((ele) => {if(ele.type == newItem.type){ return newItem } return ele});

console.log(arr);
/*
[
  {
    "size": "900.00 KB",
    "name": "Cactus.jpg",
    "documentoContentType": "image/jpeg",
    "type": "flower"
  },
  {
    "size": "500.00 KB",
    "name": "Penguins.jpg",
    "documentoContentType": "image/jpeg",
    "type": "animal"
  }
]

*/

Answer №4

The method known as filter is utilized to create a fresh array on which splice() is performed, leaving the original array untouched. Give it a try!

 const newElement = { "size": "900.00 KB", "name": "Cactus.jpg", "documentoContentType": "image/jpeg", "type": "flower" }; 
let array = [ 
  { "size": "100.34 KB", "name": "Phone.jpg", "documentoContentType": "image/jpeg", "type": "object" }, 
  { "size": "606.34 KB", "name": "Tulips.jpg", "documentoContentType": "image/jpeg", "type": "flower" }, 
  { "size": "500.00 KB", "name": "Penguins.jpg", "documentoContentType": "image/jpeg", "type": "animal" }  
];

array = array.filter(item => item.type === "flower")
  .splice(0, array.length, newElement);
  
console.log(array);  

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

What is the reason for allowing negative array indices in C programming language?

According to a discussion on Stack Overflow, it seems that C allows negative indices. Why would a programming language support such a feature that could potentially lead to memory violations? Shouldn't the compiler issue a warning for using nega ...

String arrays in Javascript with arithmetic operators

I am working with an array that contains mathematical signs. var signs = ['+', '-', '*', '/']; In addition, I have two variables representing digits to combine with each sign from the array. var right_digit = 1; v ...

Tips for displaying specific information using Javascript depending on the input value of an HTML form

I am working on an HTML form that includes a dropdown list with four different names to choose from. window.onload = function(){ document.getElementById("submit").onclick = displaySelectedStudent; } function displaySelectedStu ...

Combining both AJAX variables and HTML classes

Having trouble combining two AJAX variables with JQuery and PHP to add to a MySQL database... Here is the code snippet: $.ajax({ url: DIR+"some.php", method: "POST", dataType: "JSON", data: { mobile: mobile.val(), d ...

Select value not updating as expected

I have a select box that is linked to a switch statement in PHP, which changes the order of the results returned from the database based on the value selected in the select box. However, I am facing an issue with my JavaScript not working correctly. Can an ...

What steps can I take to resolve this state bug in React?

Looking to create a react application where pressing enter on a block adds a new block below it, pushing the existing blocks down. However, encountering an issue where pressing enter on one block causes a later block to disappear. Seeking guidance on iden ...

Comparing the use of visibility: hidden with -webkit-transform: translate3d() within a PhoneGap application

Currently, I am creating a hybrid application using PhoneGap. As part of the design, I have several divs (each representing a page) that I toggle between by changing their visibility in CSS using "visibility: hidden" and "visible". However, I recently ca ...

Using Firebase Data in Angular5 Component with MathJax Integration

I am facing an issue where I need to update the data retrieved from Firebase in a way that equations are displayed on the page instead of random symbols representing Latex syntax. While I have successfully integrated MathJax into my project through a scrip ...

Obtaining the chosen options from a dropdown menu

I am facing an issue with retrieving values from dropdown menus on a webpage that are used to filter a list. Despite trying various methods, I am not getting any values returned in my function. Here is what I have attempted: - var browserVal= document.ge ...

Issue with CKEditor 5 in Nuxt 3: "Template or render function for component is not found"

I have successfully installed the required packages: npm i @ckeditor/ckeditor5-build-classic @ckeditor/ckeditor5-vue Next, I integrated it into a component: <template> <div class="w-full h-[400px]"> <CKEditor v-mod ...

Create a div element within the parent window of the iFrame

I'm trying to figure out how I can click a button within an iFrame that contains the following code: <td class="id-center"> <div class="bs-example"> <a id="comments" href="comments.php?id=$id" name="commen ...

The endpoint throws an error, yet the HTTP subscription fails to capture it

My code seems simple enough. let body = new FormData(); body.set("a", true); body.set("username", this.user); body.set("password", this.password); let headers = new HttpHeaders(); headers.set("Content-Type", 'application/x-www-form-urlencoded') ...

Personalized JavaScript Arrays

Seeking assistance to format data received from an API. Can anyone provide guidance? fields: [ { name: "A", values: { data: [1, 2, 3, 4, 5] } }, { name: "B", values: { data: [6 ...

Enhance array algorithm to determine the maximum value of j - i while taking into account the condition A[i] <= A[j]

Given an array A[] of N positive integers, the objective is to determine the maximum value of j - i while adhering to the constraint A[i] <= A[j]. Input: The initial line includes an integer T, indicating the total number of test cases. Each test case ...

What is the best way to integrate react-final-form with material-ui-chip-input in a seamless manner

Currently, I am utilizing Material UI Chip Input wrapped with Field from react-final-form. https://i.sstatic.net/vJKM1.jpg The main objective is to restrict the number of "CHIPS" to a maximum of 5. Chips serve as concise elements representing inputs, at ...

"Facing a dilemma with Javascript's Facebox getElementById function - not fetching any

Utilizing facebox, I am initiating a small modal dialog with a form and attempting to retrieve the value from a text field on that form using javascript. Below is the HTML code: <div id="dialog-form95" style="display:none"> <div class="block"> ...

Using a function parameter to restore the values of an array

Looking to clear an array using a function parameter. Below is my implementation: <script> fruitArray = ["apple", "banana", "orange", "pineapple"] function clearFruitArray(myArr){ myArr = []; ...

Using javascript to color in cells of a grid of "pixels"

I have a project similar to an Etch-a-Sketch in progress. The main challenge I am currently facing is how to gradually darken each cell of the grid with every pass of the mouse cursor, based on the opacity of the cell being hovered over. When the grid cell ...

If Android App is not installed, divert users to a personalized web page instead of the Play Store

I am trying to create a link that opens an app on Android when clicked. However, if the app is not installed, it redirects to the Play store by default. This is not the behavior I want. What I would like is for the link to redirect to a custom webpage ins ...

What is the best way to link individual items in a dynamic list with a unique ui-sref attribute?

I have a pagination system that retrieves items from a JSON file. The items can be added or removed. I want to create a link for each item that leads to a configuration view (each item should have its own unique configuration). I am seeking the best way to ...