Remove an item from an array by value - javascript

I have an array of items like:
var items = [id: "animal", type: "cat", cute: "yes"]
And I'm trying to remove any items that match the ID given. In this case; animal
I'm stuck! I can get it to work easily by having a more simpler array but this is not what I need... I also need to remove the item by value as I don't want the hassle of referring to items by their index.
Is there a jQuery method I could use where I don't need to iterate through the items array, rather specify a selector?
Here is my jsFiddle: http://jsfiddle.net/zafrX/

I'm not sure how much of a hassle it is to refer to array items by index. The standard way to remove array items is with the splice method
for (var i = 0; i < items.length; i++)
if (items[i] === "animal") {
items.splice(i, 1);
break;
}
And of course you can generalize this into a helper function so you don't have to duplicate this everywhere.
EDIT
I just noticed this incorrect syntax:
var items = [id: "animal", type: "cat", cute: "yes"]
Did you want something like this:
var items = [ {id: "animal", type: "cat", cute: "yes"}, {id: "mouse", type: "rodent", cute: "no"}];
That would change the removal code to this:
for (var i = 0; i < items.length; i++)
if (items[i].id && items[i].id === "animal") {
items.splice(i, 1);
break;
}

No need for jQuery or any third party lib for this, now we can use the new ES5 filter :
let myArray = [{ id : 'a1', name : 'Rabbit'}, { id : 'a2', name : 'Cat'}];
myArray = myArray.filter(i => i.id !== 'a1');

You can either use splice or run a delete yourself. Here's an example:
for (var i = 0; i < items.length; i ++) {
if (items[i] == "animal") {
items.splice(i, 1);
break;
}
}

There's a simple way!
myItems.splice(myItems.indexOf(myItems.find(row => row.id == id)), 1);
Demo below:
// define function
function delete_by_id(id) {
var myItems = [{
id: 1,
type: "cat",
cute: "yes"
}, {
id: 2,
type: "rat",
cute: "yes"
}, {
id: 3,
type: "mouse",
cute: "yes"
}];
// before
console.log(myItems);
myItems.splice(myItems.indexOf(myItems.find(item => item.id == id)), 1);
// after
console.log(myItems);
}
// call function
delete_by_id(1);

You should do it like this (make sure that you have the right syntax...you cannot have array with properties, but object inside {} and then you can iterate by keys and delete unwanted key):
var items = {id: "animal", type: "cat", cute: "yes"}
var removeItem = "animal"; // or with the ID matching animal...
for(var p in items){
if(items[p] === removeItem)
delete items[p]
}
And to answer you question, you cannot apply jquery selectors to javascript objects. The best you can do to avoid for loop is to use $.each (which is a loop written in a more "functional" way).

By using object notation : http://jsfiddle.net/jrm2k6/zafrX/2/
var animal1 = {id: "animal", type: "cat", cute: "yes"}
var car2 = {id: "car", type: "pick-up", cute: "no"}
var animal3 = {id: "animal", type: "dog", cute: "yes"}
var removeItem = "animal"; // or with the ID matching animal...
var array_items = []
array_items.push(animal1);
array_items.push(car2);
array_items.push(animal3);
for(var i=0;i<array_items.length;i++){
if(array_items[i].id == removeItem){
array_items.splice(i,1);
}
}
//alert(array_items.length);

Wow, so many ideas but still not what I wanted xD
This will remove ALL entries of the given value and return the removed value:
function removeOfArray(val, arr){
var idx;
var ret;
while ((idx = arr.indexOf(val)) > -1){
arr.splice(idx, 1);
ret = val;
}
return ret;
}
Also I found other solutions here:
Remove item from array by value

-parray : list of array of object
-pstring :value to remove from the array
-ptag :using which tag we
function removeFromArr (parray,ptag,pstring){
var b =[];
var count = 0;
for (var i =0;i<parray.length;i++){
if(pstring != parray[i][ptag]){
b[count] = parray[i];
count++;
}
}
return b;
}
var lobj = [ {
"SCHEME_CODE": "MIP65",
"YEARS": "1",
"CURRENCY": "GBP",
"MAX_AMT": 200000,
"MIN_AMT": 1000,
"AER_IR": "1.80",
"FREQUENCY": "Monthly",
"CUST_TYPE": "RETAIL",
"GROSS_IR": "1.79"
},
{
"SCHEME_CODE": "MIP65",
"YEARS": "2",
"CURRENCY": "GBP",
"MAX_AMT": 200000,
"MIN_AMT": 1000,
"AER_IR": "1.98",
"FREQUENCY": "Monthly",
"CUST_TYPE": "RETAIL",
"GROSS_IR": "1.96"
},
{
"SCHEME_CODE": "MIP65",
"YEARS": "3",
"CURRENCY": "GBP",
"MAX_AMT": 200000,
"MIN_AMT": 1000,
"AER_IR": "2.05",
"FREQUENCY": "Monthly",
"CUST_TYPE": "RETAIL",
"GROSS_IR": "2.03"
},
{
"SCHEME_CODE": "MIP65",
"YEARS": "5",
"CURRENCY": "GBP",
"MAX_AMT": 200000,
"MIN_AMT": 1000,
"AER_IR": "2.26",
"FREQUENCY": "Monthly",
"CUST_TYPE": "RETAIL",
"GROSS_IR": "2.24"
},
{
"SCHEME_CODE": "QIP65",
"YEARS": "1",
"CURRENCY": "GBP",
"MAX_AMT": 200000,
"MIN_AMT": 1000,
"AER_IR": "1.80",
"FREQUENCY": "Quarterly",
"CUST_TYPE": "RETAIL",
"GROSS_IR": "1.79"
},
{
"SCHEME_CODE": "QIP65",
"YEARS": "2",
"CURRENCY": "GBP",
"MAX_AMT": 200000,
"MIN_AMT": 1000,
"AER_IR": "1.98",
"FREQUENCY": "Quarterly",
"CUST_TYPE": "RETAIL",
"GROSS_IR": "1.97"
},
]
function myFunction(){
var final = removeFromArr(lobj,"SCHEME_CODE","MIP65");
console.log(final);
}
<html>
<button onclick="myFunction()">Click me</button>
</html>
are going to remove from the objects
function removeFromArr(parray, pstring, ptag) {
var farr = [];
var count = 0;
for (var i = 0; i < pa.length; i++) {
if (pstring != pa[i][ptag]) {
farr[count] = pa[i];
count++;
}
}
return farr;
}

ES6 Solution
persons.splice(persons.findIndex((pm) => pm.id === personToDelete.id), 1);

Related

Unable to update a JSON value

I'm writing a code where I need to filter a JSON array and update a value of a key. Here is my code.
var data = [{
"Id": "1",
"ab": '123',
"afb_Educational_expense_types_for_school__c": "Books or supplies"
}, {
"Id": "2",
"ab": '343',
"afb_Educational_expense_types_for_school__c": "Mandatory fees"
}, {
"Id": "3",
"ab": '34',
}];
var itemVar = data.filter(item => item.Id == '3');
itemVar['ab'] = '22';
console.log(itemVar);
Here I'm trying to set 'ab' to 22 but it is not working. Where am I going wrong?
Your itemVar is an array, because .filter always returns an array. You have to specify that you want the first element in the array [0]
itemVar[0]['ab'] = '22';
You can use findIndex and then update the relevant item of the array:
const data = [
{ "Id": "1", "ab": '123', "afb_Educational_expense_types_for_school__c": "Books or supplies" },
{ "Id": "2", "ab": '343', "afb_Educational_expense_types_for_school__c": "Mandatory fees" },
{ "Id": "3", "ab": '34' }
];
let index = data.findIndex((item) => item.Id == '3');
if (index !== -1) data[index].ab = '22';
console.log(data);
var itemVar = data.find((item) => item.Id == '3')
itemVar.ab = '22'
Thats the easiest way to solve it.

Dynamically creating an object with an array inside

I'm trying to dynamically create a JS object which has an array inside such as this one:
//other values omitted for clarity
"items": [
{
"name": "T-Shirt",
"unit_amount": {
"currency_code": "USD",
"value": "90.00"
},
"quantity": "1",
"category": "PHYSICAL_GOODS"
},
{
"name": "Shoes",
"unit_amount": {
"currency_code": "USD",
"value": "45.00"
},
"quantity": "2",
"category": "PHYSICAL_GOODS"
}
],
I am able to create a single value with this code:
var product = {};
product.name = "T-Shirt";
product.quantity = "1";
product.category = "PHYSICAL_GOODS";
var subproduct = {};
subproduct.currency_code = "USD";
subproduct.value = "90.00";
product.unit_amount = subproduct;
var jsonString= JSON.stringify(product);
Which creates:
{
"name": "T-Shirt",
"unit_amount": {
"currency_code": "USD",
"value": "90.00"
},
"quantity": "1",
"category": "PHYSICAL_GOODS"
}
How can I add up the created values inside the array? I have an onclick event for providing the values for any given "item" in the example. For clarity, I do not know beforehand how many "items" the array will have.
To add the object to an array you should use the array method .push().
You could do it in the following way:
// Object which has a property `items`, where we will store product objects
var main = {
items: []
};
// Create the full product object
var product = {
name: "T-Shirt";
quantity: "1";
category: "PHYSICAL_GOODS";
unit_amount: {
currency_code = "USD";
value = "90.00";
}
};
// Push the new object to the `items` array
main.items.push(product);
You are on the right path, just iterate your code and put it in an array :
var productList = [];
for (var i = 0 ; i < 2; i++) {
// your code
var product = {};
product.name = "T-Shirt";
product.quantity = "1";
product.category = "PHYSICAL_GOODS";
var subproduct = {};
subproduct.currency_code = "USD";
subproduct.value = "90.00";
product.unit_amount = subproduct;
productList.push(product);
}
var answer = JSON.stringify(productList);
console.log(answer);

Looking to filter array and make them into 2 arrays based on a flag if true or false

I am planning to filter an array into 2 separate arrays based on flag in one of the inner arrays but having trouble. Please help me with my code.
How do we get 2 separate arrays out of apiData to have objects filtered in types array based on flag value
var apiData = [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
},
"id": "1.2",
"flag": false
}]
},
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}
]
My Result should be like this for filteredTrueArray [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
}]
},
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}
]
I wanted $scope.filteredTrueArray to have types array with flag=true value objects and another array to have types array with only flag=false objects. Below is my code
$scope.filteredTrueArray = apiData.filter(function(item) {
var isTrueFound = item.types.some(function (el) {
return el.flag == true;
});
if(isTrueFound){
for(var i=0;i<item.types.length>0;i++)
{
if(item.types[i].flag == true){
$scope.filteredTrueArray.push(item.types[i]);
}
}
}
});
I've written a simple filter function. Please take a look!
var apiData = [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
}, {
"id": "1.2",
"flag": false
}]
}, {
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}];
function filterByTypeFlag(records, flagValue) {
var filtered = [];
records.forEach(function (record) {
var matchedTypes = [];
record.types.forEach(function (type) {
if (type.flag === flagValue) {
matchedTypes.push(type);
}
});
if (matchedTypes.length) {
filtered.push({
"id": record.id,
"types": matchedTypes
});
}
});
return filtered;
}
filterByTypeFlag(apiData, true);
filterByTypeFlag(apiData, false);
Here is a sample code that creates an object with a boolean value and creates 2 arrays of objects bases off their boolean value. Sorry if I misunderstood what you were looking for.
var objArray = [];
class testObj {
constructor(Oname, test1) {
this.name = Oname;
this.isABoolean = test1;
objArray.push(this);
}
}
var test1 = new testObj("test1", false);
var test2 = new testObj("test2", true);
var test3 = new testObj("test3", false);
var test4 = new testObj("test4", true);
var test5 = new testObj("test5", false);
var objArray = [test1, test2, test3, test4, test5];
var trueArray = [];
var falseArray = [];
function createArrays() {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].isABoolean === true) {
trueArray.push(objArray[i]);
//console.log(trueArray[i].name);
} else if (objArray[i].isABoolean === false) {
falseArray.push(objArray[i]);
}
}
}
createArrays();
for (var j = 0; j < trueArray.length; j++) {
console.log("True value: " + trueArray[j].name);
}
for (var k = 0; k < falseArray.length; k++) {
console.log("False value " + falseArray[k].name);
}
EDIT: I cleaned it up to automatically add the objects to an array upon creation.
One solution is to use map() with a filter() for get the new types array.
var apiData = [
{
"id": 1,
"types": [
{"id": "1.1", "flag": true},
{"id": "1.2", "flag": false}
]
},
{
"id": 2,
"types": [
{"id": "2.1", "flag": true}
]
}
];
let filteredTrueArray = apiData.map(
({id, types}) => ({id, types: types.filter(x => x.flag)})
)
.filter(({types}) => types.length);
let filteredFalseArray = apiData.map(
({id, types}) => ({id, types: types.filter(x => !x.flag)})
)
.filter(({types}) => types.length);
console.log("FilteredTrueArray:", filteredTrueArray);
console.log("FilteredFalseArray:", filteredFalseArray);

reset object order javascript

I have a object like this
{
"items":{
"2":{
"id":122,
"product_id":"DE",
"price":"9.35",
},
"4":{
"id":15,
"product_id":"CH",
"price":"8.00",
}
"7":{
"id":78,
"product_id":"CH",
"price":"3.00",
}
},
"total_price":"20.35",
"item_count":2,
"unit":"CHF"
}
Do you know how i reset the items order.
now 2, 4, 7
should be 0, 1, 2
Created a JSfiddle that shows you a way.
Im using a custom format function:
function format(object) {
var items = {};
var i = 0;
for (var index in object.items) {
items[i] = object.items[index];
i++;
}
object.items = items;
}
The resulted object is this:
{
"items": {
"0": {
"id": 122,
"product_id": "DE",
"price": "9.35"
},
"1": {
"id": 15,
"product_id": "CH",
"price": "8.00"
},
"2": {
"id": 78,
"product_id": "CH",
"price": "3.00"
}
},
"total_price": "20.35",
"item_count": 2,
"unit": "CHF"
}
How about this
var obj = {
"items":{
"2":{
"id":122,
"product_id":"DE",
"price":"9.35",
},
"4":{
"id":15,
"product_id":"CH",
"price":"8.00",
},
"7":{
"id":78,
"product_id":"CH",
"price":"3.00",
}
},
"total_price":"20.35",
"item_count":2,
"unit":"CHF"
}
var keys = Object.keys(obj.items)
for (var i = 0; i < keys.length; i++) {
obj.items[i] = obj.items[keys[i]];
delete obj.items[keys[i]];
};
console.log(obj);
Object properties do not have order. I assume you want to re-name the properties, counting up from 0, but have the properties maintain the original relative ordering of their keys. (So the property with the smallest name is renamed to 0, the second-to-smallest is 1, etc.)
To do this, get all the property names, and sort the names numerically. Then, get all the values in the same over as their sorted property names. Finally, re-insert those property values with their new property names.
var itemsObj = obj["items"];
// get all names
var propertyNames = Object.keys(itemsObj);
// sort property names in numeric order: ["2", "4", "7"]
propertyNames.sort(function(a,b){ return a-b; });
// get property values, sorted by their property names
// ["2", "4", "7"] becomes [{ "id":122, .. }, { "id":15, ... }, { "id":78, ... }]
var values = propertyNames.map(function(propName) { return itemsObj[propName]; }
// clear out old property and add new property
for(var i=0; i<values.length; ++i) {
delete itemsObj[propertyNames[i]];
itemsObj[i] = values[i];
}
var data = {
"items": {
"2": {
"id": 122,
"product_id": "DE",
"price": "9.35",
},
"4": {
"id": 15,
"product_id": "CH",
"price": "8.00",
},
"7": {
"id": 78,
"product_id": "CH",
"price": "3.00",
}
},
"total_price": "20.35",
"item_count": 2,
"unit": "CHF"
};
var indices = Object.keys(data.items).map(function(i) { return parseInt(i, 10); }),
counter = 0;
indices.sort();
indices.forEach(function (i) {
if (i > counter) { // put here some more collision detecting!
data.items[counter] = data.items[i];
delete data.items[i];
counter++;
}
});
Object properties order is not guaranteed anyway. You should use an array instead.
Take a look at this answer

programmatically add object properties of arrays

[
{
"uId": "2",
"tabId": 1,
"tabName": "Main",
"points": "10"
},
{
"uId": "3",
"tabId": 2,
"tabName": "Photography",
"points": "20"
}
]
how can I insert into specified array by inspecting its properties values? says I want to add a assoc object into uId = 3, how can I do that? or it's not possible technically?
This is also possible using array.map (Added to the ECMA-262 standard in the 5th edition):
array.map(function(i){
if(i.uId == 3) i['newprop'] = 'newValue';
});
Example Here.
Update: It could be an array
if(i.uId == 3) i['newprop'] = ['newvalue1', 'newvalue2'];
Example2 Here.
They look like JSON data , so json_decode() to an array , search for the UId value and then add the corresponding assoc value and after the end finally wrap them up using json_encode()
foreach($array as $k=>&$arr)
{
if($arr->{'uId'}==2)
{
$arr->{'somecol'}="Hey";
}
}
echo json_encode($array,JSON_PRETTY_PRINT);
OUTPUT :
[
{
"uId": "2",
"tabId": 1,
"tabName": "Main",
"points": "10",
"somecol": "Hey"
},
{
"uId": "3",
"tabId": 2,
"tabName": "Photography",
"points": "20"
}
]
var array = [
{
"uId": "2",
"tabId": 1,
"tabName": "Main",
"points": "10"
},
{
"uId": "3",
"tabId": 2,
"tabName": "Photography",
"points": "20"
}
];
for ( var i = 0; i < array.length; i++ ) {
if ( array[i].uId == 3) {
array[i].someProp = "Hello";
break; // remove this line for multiple updates
}
}
Or you can make a function like this:
function getMatch(data, uid) {
for ( var i = 0; i < data.length; i++ ) {
if ( data[i].uId == 3) {
return data[i];
}
}
}
and use it like this:
getMatch(array, 3).someproperty = 4;
You can use the map function, which executes a function on each element of an array
a.map(function(el) {
if (el.uId == 3) {
el.prop = "value";
}
});
Or you can use the filter function.
// Get the array of object which match the condition
var matches = a.filter(function(x) { return x.uId == 3 });
if (matches.length > 0) {
matches[0].prop = "value";
}

Categories

Resources