Decrement ID in JSON array after deletion - javascript

I have an array stored in my local storage. It is dynamic. I'm storing the data along with an ID which gets incremented after every entry. User has an option of deleting, hence, I'm supposed to remove the corresponding element from the array. But, I want the ID to remain in ascending order. Ex:
var jsonObj = [{'id':'1','name':'Ray','email':'ray#gmail.com'},
{'id':'2','name':'Steve','email':'steve#gmail.com'},
{'id':'3','name':'Albert','email':'albert#gmail.com'},
{'id':'4','name':'Christopher','email':'chris#gmail.com'}]
I'm creating HTML divs for the above array. In case, Steve deletes his details, I want the array to be like:
var jsonObj = [{"id":1,"name":"Ray","email":"ray#gmail.com"},
{"id":2,"name":"Albert","email":'albert#gmail.com"},
{"id":3,"name":"Christopher","email":"chris#gmail.com"}]
The following code doesn't work accordingly.
for (var i=0; i<jsonObj.length; i++) {
//delete function is working fine.
jsonObj[i].id--;
break;
}

You could just iterate from the given index and decrement the id property.
function deleteItem(i) {
array.splice(i, 1);
while (i < array.length) {
array[i].id--;
i++;
}
}
var array = [{ id: '1', name: 'Ray', email :'ray#gmail.com'}, { id: '2', name: 'Steve', email: 'steve#gmail.com' }, { id: '3', name: 'Albert', email: 'albert#gmail.com' }, { id: '4', name: 'Christopher', email: 'chris#gmail.com' }];
deleteItem(1);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you start from 0, then you do not even need the ID
Ray is the 0th element, Christopher is 3rd
delete Albert and Christopher is 2nd
var jsObj = [{'name':'Ray','email':'ray#gmail.com'},
{'name':'Steve','email':'steve#gmail.com'},
{'name':'Albert','email':'albert#gmail.com'},
{'name':'Christopher','email':'chris#gmail.com'}]
for (var i=0;i<jsObj.length;i++) {
document.write("<br>ID"+(i+1)+": "+jsObj[i].name)
}
document.write("<hr/>");
jsObj.splice(2, 1); // Bye bye Albert
for (var i=0;i<jsObj.length;i++) {
document.write("<br>ID"+(i+1)+": "+jsObj[i].name)
}
More information
Reindex javascript array / object after removing a key

You just declare a new variable in your for loop which you will increment it and you assign this value as their id
for (var i=0, id=1; i<jsonObj.length; i++, id++) {
var jsonObj = [{'id':'1','name':'Ray','email':'ray#gmail.com'},
{'id':'2','name':'Steve','email':'steve#gmail.com'},
{'id':'3','name':'Albert','email':'albert#gmail.com'},
{'id':'4','name':'Christopher','email':'chris#gmail.com'}];
console.log(jsonObj);
jsonObj.splice(1, 1);
for (var i=0, id=1; i<jsonObj.length; i++, id++) {
jsonObj[i].id = id;
}
console.log(jsonObj);

a very simplistic approach could be:
// the index of the deleted element
const delIndex = 2;
// reindex all entries starting from deleted one
for (var i=delIndex+1; i<jsonObj.length; i++) {
jsonObj[i].id = i + 1;
}
The id basically corresponds with the array index anyway. So instead of trying to compute the id anew, we can just overwrite it with the respective index (+1 as you start with one and not zero like array indices).

for your requirements you have to use the splice method in the javascript
array.splice(index_you_wantto_delete,count)
ex:-jsonObj.splice(1,1);
The splice() method adds/removes items to/from an array,

Here is a verbose solution explaining the process step by step
1- Delete the element
2 - Update the indexes if the element was found and deleted
/**
*
* #param array list Your list
* #param int elementID The id of the element you want to remove
* #returns list The list with the element removed and the indexes rearanged
*/
var deleteElement = function (list, elementID) {
var removedIndex = false;
for (var index = 0; index < list.length; index++) {
if (list[index]['id'] === elementID) {
list.slice(index, 1);
removedIndex = index;
break;
}
}
if (removedIndex !== false) {
//Get last id
var lastElement = (removedIndex === 0) ? null : list[removedIndex - 1];
// Set to 0 if the first element was removed
var lastID = (lastElement === null) ? 0 : lastElement.id;
for (var i = removedIndex; i < list.length; i++) {
list[i].id = ++lastID;
}
}
return list;
};

Try the below method. Hope it works !!
// index of the deleted item
var itemDeleted = 2;
// create a for loop from deleted index till last
for (var i = itemDeleted-1; i < jsonObj.length; i++) {
jsonObj[i].id = i+1;
}

You can do in pure js by using map
const jsonObj = [{
'name': 'Ray',
'email': 'ray#gmail.com'
},
{
'name': 'Steve',
'email': 'steve#gmail.com'
},
{
'name': 'Albert',
'email': 'albert#gmail.com'
},
{
'name': 'Christopher',
'email': 'chris#gmail.com'
}
];
jsonObj.splice(1, 1);
const newObj = jsonObj.map((c, i) => ({
name: c.name,
email: c.email,
id: i + 1
}));
console.log(newObj);

Get the deleted index and assign it to the i value of for loop
for (var i=deletedIndex; i<jsonObj.length; i++) {
jsonObj[i].id--;
}

Related

Compute the what was added or remove from new and original array

this seems pretty silly to ask but I'm moving a bit away from PHP to javascript and have a bit of a hard time with 2 arrays one the original values and the other the new values.
I need to take take action on any values removed (run some function) and on any new values that where added.
Here is what I came up with so far, but it doesn't seem right.
// new values
var array1 = [ 'aaaa', 'R26i9vjDHE', 'bbbbb' ];
// original values
var array2 = [ 'U8G5AQVsX6', 'R26i9vjDHE', '7IkuofIHEu','aaaa'];
for (var i = 0; i < array2.length; i++) {
if(array1.indexOf(array2[i]) != -1) {
console.log('in new already?');
console.log(array2[i])
// do something with new inserted value
} else {
console.log('removed items');
console.log(array2[i])
// do something with a removed value
}
}
I'm used to php's in_array in a loop or various other php tool box items.
Suggestions?
my fiddle https://jsfiddle.net/xv8ah2yf/8/
So an element that was removed will be in array2, but not array1, and then an element added will be in array1 but not array2. So to detect both cases you'll need to loop through both arrays. You can do something like
var i;
for (i = 0; i < array2.length; i++) {
if (array1.indexOf(array2[i]) === -1) {
//item removed from array2
console.log(array2[i] + ' removed');
}
}
for (i = 0; i < array1.length; i++) {
if (array2.indexOf(array1[i]) === -1) {
//item added to array1
console.log(array1[i] + ' added');
}
}
Then take the appropriate action when each case is detected.
Let's just define what is meant be "added" and "removed":
added: in new array but not in original.
removed: in original but not in new array.
We can use 2 for-loops to determine these two types of elements:
let original_array = ['abc', 'def', 'ghi'];
let new_array = ['def', 'jkl', 'mno'];
for (let i = 0; i < new_array.length; i++){
if (!original_array.includes(new_array[i])){
console.log(new_array[i], 'has been added');
//further actions...
}
}
for (let i = 0; i < original_array.length; i++){
if (!new_array.includes(original_array[i])){
console.log(original_array[i], 'has been removed');
//further actions...
}
}
This should do it:
function compute(original, modified, addedCB, removedCB) {
for (let i of modified) {
if (!original.includes(i)) {
// this is a new value
addedCB(i);
}
}
for (let i of original) {
if (!modified.includes(i)) {
// the modified array doesn't include this value
removedCB(i);
}
}
}
You can get close to PHP's in_array with javascript's array.includes. You can use that to then filter the arrays in question:
This is a little slower than doing everything in a for loop, but also more succinct and cleared (IMO):
// new values
var array1 = [ 'aaaa', 'R26i9vjDHE', 'bbbbb' ];
// original values
var array2 = [ 'U8G5AQVsX6', 'R26i9vjDHE', '7IkuofIHEu','aaaa'];
// in array1 but not in array2
let not_in_array2 = array1.filter(item => !array2.includes(item))
// in array2 but not in array1
let not_in_array1 = array2.filter(item => !array1.includes(item))
// in both arrays
let inBoth = array1.filter(item => array2.includes(item))
console.log("Not in array1:", not_in_array1)
console.log("Not in array2:", not_in_array2)
console.log("In both:", inBoth)
From there you can forEach() or map() over the results and apply whatever function you want.

Splice not being called in loop, id not found in array

I'm trying to splice an array by parameter given from an onClick element like deleteFavourite(2). Three console logs show: id (2), fired message, and saved message, but the spliced message is ignored. Why is it not hitting the if?
Function:
deleteFavourite: function (id) {
console.log(id);
console.log("fired");
var array = this.favourites;
for (var i = 0; i < array.length; i++) {
if (array[i] === id) {
array.splice(i, 1);
console.log("spliced");
}
}
this.save();
console.log("saved");
}
The array is outputted like this in Chrome
Array(3)
0: {id: 0, title: "↵Page 0 ", url: "/page-0/"}
1: {id: 1, title: "↵Social media ", url: "/social-media/"}
2: {id: 2, title: "↵Get involved ", url: "/get-involved/"}
length: 3
__proto__: Array(0)
Because you're working with an array containing plain objects, so your control should be:
deleteFavourite: function (id) {
console.log(id);
console.log("fired");
var array = this.favourites;
for (var i = 0; i < array.length; i++) {
if (array[i].id === id) {
array.splice(i, 1);
console.log("spliced");
}
}
this.save();
console.log("saved");
}
Indeed, you want to compare the id inside the array with the int you passed as a parameter.
Otherwise, you're comparing an object (the array[i] is an object containing 3 attributes) to an int, which will never result as true.
I guess you don't need to loop your array for that. To make it work as it is try to not compare in if statement the whole section of array to a number but only iteration of your array with a number. In my opinion this should look like this first check if element of array exist then slice it.
if (array[id]) {
array.splice(id, 1);
console.log("spliced");
}
Try:
deleteFavourite: function (id) {
console.log("deleteFavourite: ", id);
var array = this.favourites;
for (var i = 0; i < array.length; i++) {
if (array[i].id === id) { // <---- MY CHANGE
array.splice(i, 1);
console.log("spliced");
}
}
this.save();
console.log("saved");
}
You should have used array[i].id since the index of the items in your array does not match the actual id index.
Using ES2015 findIndex:
deleteFavourite: function (id) {
var array = this.favourites,
index = array .findIndex(item => item.id == id);
if( index > -1 ){
array.splice(index, 1);
this.save();
}
}

How can I find which index in an array contains an object whose value for a specific key is x? [duplicate]

I would like to find index in array. Positions in array are objects, and I want to filter on their properties. I know which keys I want to filter and their values. Problem is to get index of array which meets the criteria.
For now I made code to filter data and gives me back object data, but not index of array.
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var filterparams = {userid:'7', chid: 'default'};
function getIndexOfArray(thelist, props){
var pnames = _.keys(props)
return _.find(thelist, function(obj){
return _.all(pnames, function(pname){return obj[pname] == props[pname]})
})};
var check = getIndexOfArray(data, filterparams ); // Want to get '2', not key => val
Using Lo-Dash in place of underscore you can do it pretty easily with _.findIndex().
var index = _.findIndex(array, { userid: '7', chid: 'default' })
here is thefiddle hope it helps you
for(var intIndex=0;intIndex < data.length; intIndex++){
eachobj = data[intIndex];
var flag = true;
for (var k in filterparams) {
if (eachobj.hasOwnProperty(k)) {
if(eachobj[k].toString() != filterparams[k].toString()){
flag = false;
}
}
}
if(flag){
alert(intIndex);
}
}
I'm not sure, but I think that this is what you need:
var data = [{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
}, {
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}];
var filterparams = {userid:'7', chid: 'default'};
var index = data.indexOf( _.findWhere( data, filterparams ) );
I don't think you need underscore for that just regular ole js - hope this is what you are looking for
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var userid = "userid"
var filterparams = {userid:'7', chid: 'default'};
var index;
for (i=0; i < data.length; i++) {
for (prop in data[i]) {
if ((prop === userid) && (data[i]['userid'] === filterparams.userid)) {
index = i
}
}
}
alert(index);

remove duplicated value from array and replace it with the latest value in javascript

I have an array in JavaScript. The user enters string and the data placed in this array in the form of value and name.
if(!_.isUndefined(args[1]) && !_.isUndefined(args[2])) {
if(args[1].length !== 0 && args[2].length !== 0) {
var dataObj = {
name : args[1],
value : args[2]
};
formateArray.push({name: dataObj.name, value:dataObj.value});
How can I remove duplicated value from array and replace it with the latest value the user enters?
So when the user enters: value_1 100, value_2 200, value_1 500
I expect to see: value_1 500, value_2 200 (replace the duplicates with new data)
You can iterate your array replace the value if the name already exists.
function push(array, newVal) {
var found = false;
for (var i = 0; i < array.length && !found; i++) {
if (array[i].name === newVal.name) {
array[i].value = newVal.value;
found = true;
}
}
if (!found) {
array.push(newVal);
}
}
function printNameValue(array) {
var out = '';
for (var i = 0; i < array.length; i++) {
out += array[i].name + ' ' + array[i].value + ', ';
}
return out;
}
var myArray = [];
push(myArray, {
name: 'value_1',
value: 100
});
push(myArray, {
name: 'value_2',
value: 200
});
push(myArray, {
name: 'value_1',
value: 500
});
alert(printNameValue(myArray));
Since your values can be associated with meaningful keys, perhaps you should use an object map rather than an array to store your values. Avoiding duplicates now becomes trivial since you cannot have duplicate keys.
var valuesMap = {};
//setting value
valuesMap.value_1 = 100;
//setting another value
valuesMap.value_2 = 200;
//replacing it
valuesMap.value_1 = 500;
Otherwise it's still quite simple, but less efficient:
function add(arr, obj) {
var key = obj.name, i, len;
for (i = 0, len = arr.length; i < len; i++) {
if (arr[i].name === key) {
arr[i] = obj;
return;
}
}
arr.push(obj);
}
var values = [];
add(values, { name: 'test', value: 1 });
add(values, { name: 'test', value: 2 });
values.length; //1
Instead of the array object, i suggest you to use an object that will act like a hashtable. You can define on this way var formateArray = {};
When you want to add or edit the data, instead of using push, you can do it like this:
formateArray[dataObj.name] = {name: dataObj.name, value:dataObj.value};
If the key does not exist dataObj.name, it will be added. It the key exist, the value would set with the new value.
If you want the size of you array, you get it this way Object.keys(formateArray).length
If you want to loop on your data, you can do it this way:
for (var k in formateArray) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (formateArray.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + formateArray[k].value);
}
}
Here is a jsfiddle that illustrate this.

sort entries of a drop down alphabitically

I am dynamically adding drop entries to a drop down by using following code.
var x =document.getElementById("x");
var optn = document.createElement("OPTION");
optn.text="hhh";
optn.value="val";
x.add(optn);
The above thing is done in a loop
Now i want to sort it alphabatically.How can i do it?
It would be easier to sort the array before adding the options to the dropdown. Moving DOM elements around once they are added would be less efficient. For example:
var arr = [ { id: '1', value: 'B' },
{ id: '2', value: 'A' },
{ id: '3', value: 'C' } ];
arr.sort(function(a, b) {
if (a.value < b.value) {
return -1;
}
if (a.value > b.value) {
return 1;
}
return 0;
});
for (var i = 0; i < arr.length; i++) {
// TODO: the array is now sorted => build the dropdown here
}
public void SortDropDownList(DropDownList ddl)
{
//create a ListItem array the size of the items
//in your DropDownList
ListItem[] sorted = new ListItem[ddl.Items.Count];
//loop through all the items in your ListItem array
for (int i = 0; i < sorted.Length; i++)
{
//resize the array on each iteration
Array.Resize(ref sorted, i);
//add the current index to the array
sorted[i] = ddl.Items[i];
}
//call Array.Sort to sort your ListItem array
Array.Sort(sorted);
//remove all items from the DropDownList
ddl.Items.Clear();
//add the sorted items to the DropDownList
ddl.Items.AddRange(sorted);
}
u use the help of this function after the all items bound to the dropdownlist

Categories

Resources