remove item from array using its name / value - javascript

I have the following array
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
How can I remove an item from this array using its name or id ?
Thank you

Created a handy function for this..
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
array.splice(index, 1);
}
});
}
//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');

Array.prototype.removeValue = function(name, value){
var array = $.map(this, function(v,i){
return v[name] === value ? null : v;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
countries.results.removeValue('name', 'Albania');

Try this:
var COUNTRY_ID = 'AL';
countries.results =
countries.results.filter(function(el){ return el.id != COUNTRY_ID; });

Try this.(IE8+)
//Define function
function removeJsonAttrs(json,attrs){
return JSON.parse(JSON.stringify(json,function(k,v){
return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);

You can delete by 1 or more properties:
//Delets an json object from array by given object properties.
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); ->
//removes all items with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
var deleted = 0;
for (var i = 0, count = indexes.length; i < count; i++) {
this.splice(indexes[i], 1);
deleted++;
}
return deleted;
}

you can use delete operator to delete property by it's name
delete objectExpression.property
or iterate through the object and find the value you need and delete it:
for(prop in Obj){
if(Obj.hasOwnProperty(prop)){
if(Obj[prop] === 'myValue'){
delete Obj[prop];
}
}
}

This that only requires javascript and appears a little more readable than other answers.
(I assume when you write 'value' you mean 'id')
//your code
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
// solution:
//function to remove a value from the json array
function removeItem(obj, prop, val) {
var c, found=false;
for(c in obj) {
if(obj[c][prop] == val) {
found=true;
break;
}
}
if(found){
delete obj[c];
}
}
//example: call the 'remove' function to remove an item by id.
removeItem(countries.results,'id','AF');
//example2: call the 'remove' function to remove an item by name.
removeItem(countries.results,'name','Albania');
// print our result to console to check it works !
for(c in countries.results) {
console.log(countries.results[c].id);
}

it worked for me..
countries.results= $.grep(countries.results, function (e) {
if(e.id!= currentID) {
return true;
}
});

You can do it with _.pullAllBy.
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
// Remove element by id
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');
// Remove element by name
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');
console.log(countries);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Maybe this is helpful, too.
for (var i = countries.length - 1; i--;) {
if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
countries.splice(i, 1);
}
}

The accepted answer is problematic as it attaches a function to the Array prototype. That function will show up whenever you run thru the array using a for loop:
for (var key in yourArray) {
console.log(yourArray[key]);
}
One of the values that will show up will be the function. The only acceptable way to extend base prototypes (although it is generally discouraged as it pollutes the global space) is to use the .defineProperty method:
Object.defineProperty(Object.prototype, "removeValue", {
value: function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
},
writable: true,
configurable: true,
enumerable: false
});

Related

how to check whether string is availble in array or not

I have one array
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
Now I want to check whether "ghi" and "mno" is there or not in array. If there then what is the value.
This is how to do it:
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
for(var child in arr){
console.log(arr[child].includes("mno"));
}
Edit, for old browser you can do it this way:
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
for(var child in arr){
console.log(arr[child].search("mno"));
}
Where 0 is equal to true ^^
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
function valueOf (array, key) {
var value;
if (array.find(function (item) {
return ([ , value ] = item.split("="))[0] === key
})) {
return value;
}
}
console.log(valueOf(arr, "ghi")); // 3
console.log(valueOf(arr, "mno")); // 9
console.log(valueOf(arr, "foo")); // undefined
Using lodash
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
var r = _.find(arr, function(i) { return i.includes('ghi'); });
alert(r);
DEMO
You could use Array.prototype.find() and String.prototype.includes()
arr.find(function(item) {
if(typeof item === "string" && item.includes("asd")) {
return true;
}
return false;
});
Now if an item was found, you can assume that the string was found in the array.
Loop through the array and check each string.
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var arr = ["abc=0","def=2","ghi=3","jkl=6","mno=9"];
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var pos_of_ghi = searchStringInArray("ghi", arr );
var pos_of_mno = searchStringInArray("mno", arr );
if(pos_of_ghi ==-1){
alert("ghi not found")
}
else{
alert("pos_of_ghi="+pos_of_ghi);
}
if(pos_of_mno ==-1){
alert("mno not found")
}
else{
alert("pos_of_mno="+pos_of_mno);
}
the best and simple logic is:
arr.find(function(item) {
return (typeof item === "string" && item.includes("ghi"));
});

reduce key value pairs in JS Array to object

I have one object that I had to take apart into two arrays to handle properly.
It looked like this:
{
city:"stuttgart",
street:"randomstreet",
...
}
Since it needs to fit a certain directive I had to convert it to:
[
{key:"city", value:"stuttgart"}
{key:"street", value:"randomstreet"},
...
]
for this I first used
var mapFromObjectWithIndex = function (array) {
return $.map(array, function(value, index) {
return [value];
});
};
var mapFromObjectWithValue = function (array) {
return $.map(array, function(value, index) {
return [index];
});
});
to create two arrays, one containing the old key, the other one is holding the old value. Then I created another, two dimensional array map them into a single array doing this
var mapToArray = function (arrayValue, arrayIndex) {
var tableData = [];
for (var i = 0; i<arrayIndex.length; i++){
tableData[i] = {key:arrayIndex[i] , value:arrayValue[i]};
}
return tableData;
};
(maybe I have already messed up by here, can this be done any easier?)
Now, I use the array (tableData) to display the data in a form. The value fields can be edited. In the end, I want to convert the array (tableData) to its original. (see first object)
Please note, that the original object doesn't only contain strings as values, but can also contain objects as well.
I think conversion can be definitely easier:
var obj = {
city:"stuttgart",
street:"randomstreet",
};
var tableData = Object.keys(obj).map(k => {return {key: k, value: obj[k]}});
console.log(tableData);
var dataBack = {};
tableData.forEach(o => dataBack[o.key] = o.value);
console.log(dataBack);
What do you want to do with objects? Do you want to expand them as well? If yes you can do something like this (and it works with nested objects as well):
var obj = {
city:"stuttgart",
street:"randomstreet",
obj: {a: 'a', b: 'b'},
subObject: {aha: {z: 'z', y: 'y'}}
};
function trasformToTableData(obj) {
if (typeof obj !== 'object') return obj;
return Object.keys(obj).map(k => {return {key: k, value: trasformToTableData(obj[k])}});
}
var tableData = trasformToTableData(obj);
console.log(tableData);
function transformBack(obj) {
if (Array.isArray(obj)) {
var support ={};
for (let i = 0; i < obj.length; i++) {
support[obj[i].key] = transformBack(obj[i].value)
}
return support;
}
return obj;
}
var dataBack = {};
tableData.forEach(o => dataBack[o.key] = transformBack(o.value));
console.log(dataBack);
Let's have some fun and turn our object into iterable to do the job as follows;
var input = {city:"stuttgart", street:"randomstreet", number: "42"};
output = [];
input[Symbol.iterator] = function*(){
var ok = Object.keys(this),
i = 0;
while (i < ok.length) yield {key : ok[i], value: this[ok[i++]]};
};
output = [...input];
console.log(output);
This function will map your object to an array when you call objVar.mapToArray(), by using Object.keys() and .map()
Object.prototype.mapToArray = function() {
return Object.keys(this).map(function(v) {
return { key: v, value: this[v] };
}.bind(this));
}
I would do something like this:
var dataObj = {
city:"stuttgart",
street:"randomstreet",
};
function toKeyValue(obj) {
var arr = [];
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
arr.push({'key': key, 'value': obj[key]});
}
}
return arr;
}
var arrayKeyValue = toKeyValue(dataObj);
console.log(arrayKeyValue);

push only unique elements in an array

I have array object(x) that stores json (key,value) objects. I need to make sure that x only takes json object with unique key. Below, example 'id' is the key, so i don't want to store other json objects with 'item1' key.
x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}]
var clickId = // could be "item1", "item2"....
var found = $.inArray(clickId, x); //
if(found >=0)
{
x.splice(found,1);
}
else{
x.push(new Item(clickId, obj)); //push json object
}
would this accomplish what you're looking for? https://jsfiddle.net/gukv9arj/3/
x = [
{"id":"item1","val":"Items"},
{"id":"item1","val":"Items"},
{"id":"item2","val":"Items"}
];
var clickId = [];
var list = JSON.parse(x);
$.each(list, function(index, value){
if(clickId.indexOf(value.id) === -1){
clickId.push(value.id);
}
});
You can't use inArray() because you are searching for an object.
I'd recommend rewriting a custom find using Array.some() as follows.
var x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}]
var clickId = "item1";
var found = x.some(function(value) {
return value.id === clickId;
});
alert(found);
Almost 6 years later i ended up in this question, but i needed to fill a bit more complex array, with objects. So i needed to add something like this.
var values = [
{value: "value1", selected: false},
{value: "value2", selected: false}
//there cannot be another object with value = "value1" within the collection.
]
So I was looking for the value data not to be repeated (in an object's array), rather than just the value in a string's array, as required in this question. This is not the first time i think in doing something like this in some JS code.
So i did the following:
let valueIndex = {};
let values = []
//I had the source data in some other and more complex array.
for (const index in assetsArray)
{
const element = assetsArray[index];
if (!valueIndex[element.value])
{
valueIndex[element.value] = true;
values.push({
value: element.value,
selected: false
});
}
}
I just use another object as an index, so the properties in an object will never be repated. This code is quite easy to read and surely is compatible with any browser. Maybe someone comes with something better. You are welcome to share!
Hopes this helps someone else.
JS objects are great tools to use for tracking unique items. If you start with an empty object, you can incrementally add keys/values. If the object already has a key for a given item, you can set it to some known value that is use used to indicate a non-unique item.
You could then loop over the object and push the unique items to an array.
var itemsObj = {};
var itemsList = [];
x = [{"id":"item1","val":"foo"},
{"id":"item2","val":"bar"},
{"id":"item1","val":"baz"},
{"id":"item1","val":"bez"}];
for (var i = 0; i < x.length; i++) {
var item = x[i];
if (itemsObj[item.id]) {
itemsObj[item.id] = "dupe";
}
else {
itemsObj[item.id] = item;
}
}
for (var myKey in itemsObj) {
if (itemsObj[myKey] !== "dupe") {
itemsList.push(itemsObj[myKey]);
}
}
console.log(itemsList);
See a working example here: https://jsbin.com/qucuso
If you want a list of items that contain only the first instance of an id, you can do this:
var itemsObj = {};
var itemsList = [];
x = [{"id":"item1","val":"foo"},
{"id":"item2","val":"bar"},
{"id":"item1","val":"baz"},
{"id":"item1","val":"bez"}];
for (var i = 0; i < x.length; i++) {
var item = x[i];
if (!itemsObj[item.id]) {
itemsObj[item.id] = item;
itemsList.push(item);
}
}
console.log(itemsList);
This is late but I did something like the following:
let MyArray = [];
MyArray._PushAndRejectDuplicate = function(el) {
if (this.indexOf(el) == -1) this.push(el)
else return;
}
MyArray._PushAndRejectDuplicate(1); // [1]
MyArray._PushAndRejectDuplicate(2); // [1,2]
MyArray._PushAndRejectDuplicate(1); // [1,2]
This is how I would do it in pure javascript.
var x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}];
function unique(arr, comparator) {
var uniqueArr = [];
for (var i in arr) {
var found = false;
for (var j in uniqueArr) {
if (comparator instanceof Function) {
if (comparator.call(null, arr[i], uniqueArr[j])) {
found = true;
break;
}
} else {
if (arr[i] == uniqueArr[j]) {
found = true;
break;
}
}
}
if (!found) {
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
};
u = unique(x, function(a,b){ return a.id == b.id; });
console.log(u);
y = [ 1,1,2,3,4,5,5,6,1];
console.log(unique(y));
Create a very readable solution with lodash.
x = _.unionBy(x, [new Item(clickId, obj)], 'id');
let x = [{id:item1,data:value},{id:item2,data:value},{id:item3,data:value}]
let newEle = {id:newItem,data:value}
let prev = x.filter(ele=>{if(ele.id!=new.id)return ele);
newArr = [...prev,newEle]

Make array objects all have the same keys

I have a array of object
var arr =
[
{"shares":50,"comments":10},
{"likes":40,"shares":30},
{"comments":10}
];
I want to convert it to
var arr =
[
{"shares":50,"comments":10,"likes":0},
{"likes":40,"shares":30,"comments":0},
{"comments":10,"likes":0,"shares":0}
]
Properties are not fixed numbers and names would be different see another example
var arr2 = [{"a":1},{"b":2},{"c":3},{"d":4},{"e":5},{"f":6}]
to
var arr2 = [{"a":1,"b":0,"c":0,"d":0,"e":0,"f":0},{"a":0,"b":1,"c":0,"d":0,"e":0,"f":0},{"a":0,"b":0,"c":1,"d":0,"e":0,"f":0},{"a":0,"b":0,"c":0,"d":1,"e":0,"f":0},{"a":0,"b":0,"c":0,"d":0,"e":1,"f":0},{"a":0,"b":0,"c":0,"d":0,"e":0,"f":1}]
I can do by iterating all elements of array and keys of every element but I don't know that, is it best way?
Is there any inbuilt function in JavaScript or jQuery?
You can use http://api.jquery.com/jquery.extend/
var defaults = { "shares" : 0, "comments" : 0, "likes" : 0 };
arr = $.map( arr, function( item ){
return $.extend( {}, defaults, item );
});
http://jsfiddle.net/L74q3ksw/
Edit re: updated question
Now it's a matter of building the defaults object which, as I understand, has all the unique keys from all the elements in your array.
So, given
var arr2 = [{"a":1},{"b":2},{"c":3},{"d":4},{"e":5},{"f":6}]
you need to extract "a", "b", "c", "d"... etc and create the defaults.
var defaults = {};
// collect all the keys and set them with value = 0 in defaults
arr2.forEach( function( item ){
Object.keys( item ).forEach( function( key ){
defaults[ key ] = 0;
});
});
// same as the previous solution
arr2 = $.map( arr2, function( item ){
return $.extend( {}, defaults, item );
});
http://jsfiddle.net/7dtfzg2f/2/
It looks like you want
var set = {}; // it will be cleaner with ES6 Set
$.each(arr, function(_,e){
for (var k in e) set[k] = 1;
});
$.each(set, function(k){
$.each(arr, function(_,e){
if (e[k]===undefined) e[k] = 0;
});
});
Demonstration
With pure JavaScript:
var defaults = { "shares": 0, "comments": 0, "likes": 0 };
var arr = [{"shares":50,"comments":10},{"likes":40,"shares":30},{"comments":10}];
arr.slice().map(function(e) {
for (var key in defaults) {
e[key] = e[key] || defaults[key];
}
return e;
});
This keeps you original array as it was. If you want to change your original array you can do following:
var defaults = { "shares": 0, "comments": 0, "likes": 0 };
var arr = [{"shares":50,"comments":10},{"likes":40,"shares":30},{"comments":10}];
arr.forEach(function(e) {
for (var key in defaults) {
e[key] = e[key] || defaults[key];
}
});
You can get the default values from the array with following snippet:
var defaults = arr.reduce(function(m,v) {
for (var key in v) {
m[key] = 0;
}
return m;
}, {});
Just add the key with value, if it not exists:
$(function() {
var arr = [{"shares":50,"comments":10},{"likes":40,"shares":30},{"comments":10}];
$.each(arr, function(idx, obj) {
if (typeof obj.shares === 'undefined') {
obj.shares = 0;
}
if (typeof obj.comments === 'undefined') {
obj.comments = 0;
}
if (typeof obj.likes === 'undefined') {
obj.likes = 0;
}
arr[idx] = obj;
});
console.log(arr);
});
Building on what #dusky said, if you don't actually know what columns will be coming in, you can make a list of columns as a string set. Also assumes you just want to edit the existing array, not make a new one, and use ES6.
// get all keys added to a list that cannot take duplicates
const columnNames = new Set<string>();
arr.forEach(element => {
Object.keys(element)
.forEach(x => columnNames.add(x));
});
// create default with nulls, can replace with 0 or anything here
const defaultKeys = {};
columnNames.forEach(x => {
defaultKeys[x] = null;
});
// Add all missing keys into each object
arr.forEach((element) => {
for (const key in defaultKeys) {
element[key] = element[key] || defaultKeys[key];
}
});

Listing keys containing a given string?

Given data such as :
var people = [
{ 'myKey': 'John Kenedy', 'status': 1 },
{ 'myKey': 'Steeven Red', 'status': 0 },
{ 'myKey': 'Mary_Kenedy', 'status': 3 },
{ 'myKey': 'Carl Orange', 'status': 0 },
{ 'myKey': 'Lady Purple', 'status': 0 },
... // thousands more
];
How to efficiently get the list of all objects which contains in myKey the string Kenedy ?
http://jsfiddle.net/yb3rdhm8/
Note: I currently use str.search() :
The search("str") returns the position of the match. Returns -1 if no match is found.
to do as follow :
var map_partial_matches = function(object, str){
var list_of_people_with_kenedy = [] ;
for (var j in object) {
if (object[j]["myKey"].search(str) != -1) {
object[j].presidentName = "yes"; // do something to object[j]
list_of_people_with_kenedy.push({ "people": object[j]["myKey"] }); // add object key to new list
}
} return list_of_people_with_kenedy;
}
map_partial_matches(people, "Kenedy");
I could do the same using str.match() :
str.match() returns the matches, as an Array object. Returns null if no match is found.
It works anyway, but I have no idea if it's efficient or completely dump.
You can use filter():
var filtered = people.filter(function (item) {
if (item.myKey.indexOf("Kenedy") != -1)
return item;
});
You can also checkout Sugar.js
In order to search your unsorted object you need to get through all of it's properties - So I'd say a simple loop with an indexOf will be pretty much the best you can go:
var foundItems = [];
for(var i = 0; i < people.length ;i++)
{
if(people[i].myKey.indexOf('Kenedy') > -1)
foundItems.push(people[i]]);
}
Maybe you can tweak it up a little, but it's pretty much the best you can get.
You can write a basic function that uses filter to return an array of matches based on a key and value:
function find(arr, key, val) {
return arr.filter(function (el) {
return el[key].indexOf(val) > -1;
});
}
var result = find(people, 'myKey', 'Kenedy');
Alternatively use a normal for...loop:
function find(arr, key, val) {
var out = [];
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i][key].indexOf(val) > -1) {
out.push(arr[i]);
}
}
return out;
}
DEMO
Does the Object Contain a Given Key?
function hKey(obj, key) {
arr = [];
// newarr =[];
for(el in obj){
arr.push(el)
} //return arr;
for(i=0; i<arr.length; i++){
name = arr[i]
} if(name == key) {
return true;
}else {
return false;
}
}
console.log(hKey({ a: 44, b: 45, c: 46 }, "c"))

Categories