im new to solidity and im trying to figure out the best way to splice an array.
in javascript you have: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
is there a similar way to achieve this in solidity?
the only way i think it would be possible is if you overwrite the value at the array index and replace that value with the value of the item at the next index... then do this for every following index value until the end of the array.
that method sounds like it could be expensive. does anyone have an suggestions of how to better achieve this?
the main thing i am trying to achieve is a way to keep the order of the array even though you can remove items from the middle.
suggestion 1
so thinking about it, how about using a list of structs. for example given a list of strings we want in an array, how about the data be stored into a struct with an additional bool field deleted.
struct Queue {
string value;
bool deleted;
}
Queue[] public listOfItems;
function deleteItem(uint index) public {
Queue[index].deleted = true;
}
given that read operations are free on ethereum, i can get the client to request data from some index, if the data at that index has been marked as deleted, automatically request the subsequent index until a record is found that isn't deleted.
solution 2
i could use linked lists to achieve a similar functionality. this way if an item is to be marked as deleted, i could update the key of the next item in the array.
uint counter;
mapping (uint => string) public comments;
function addComment(string newComment) public {
comments[counter + 1](newComment);
comments[counter].nextItem = counter + 1;
}
function removeCommentWithId(uint commentId) public {
comments[commentId - 1].nextItem = commentId + 1;
}
suggestion 1i have added in question body. – X0r0N Mar 18 '18 at 19:53deleteItem(uint index)for the client to request a particular index to be removed from the array. so in answer to your question, i would be "directly jumping to that node". there is no mapping involved. – X0r0N Mar 18 '18 at 21:13indexmeans the position relative to the first element of the list? (E.g. the first item is index 0, the second index 1, etc.) If so, how does the caller now theindexof an item, given that the indexes will change when items are removed? – user19510 Mar 18 '18 at 21:34indexthe same? (That would necessitate a mapping of indexes to their nodes in the list.) – user19510 Mar 18 '18 at 21:34indexvalue itself does not matter. the goal is just to retain the order. this is to know if items are added before or after each other. – X0r0N Mar 18 '18 at 21:40suggestion 2but your example seem far better thought out. i will test it out. – X0r0N Mar 18 '18 at 22:51