remove duplicate value existing object from multidimensional array object in javascript - javascript

This is my javascript array:
[{
"id": "44",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id": "47",
"name": "chathura"
}, {
"id": "20",
"name": "yasith"
}, {
"id": "21",
"name": "thisaru"
}, {
"id": "42",
"name": "insaf"
}, {
"id": "63",
"name": "sunimal"
}, {
"id": "78",
"name": "yasith"
}, {
"id": "36",
"name": "thisaru"
}]
I want to remove duplicate name existing object element from this array and get the following:
[{
"id": "47",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id ": "20",
"name ": "yasith "
}, {
"id ": "21 ",
"name ": "thisaru"
}, {
"id ": "42 ",
"name ": "insaf"
}]
How can I remove duplicates?

You can iterate through the array and use a hash table to filter any IDs that have already been used:
function getUniqueNames(nameObjects) {
var existingIds = { };
return nameObjects
.filter(function(nameObject) {
var id = nameObject.id;
var alreadyExists = existingIds[id];
existingIds[id] = true;
return alreadyExists;
});
I'm not sure about your use case, but it might make sense in your case just to convert the data into a Map. Maps work similar to a hash table, and will map each name to its ID. They enforce uniqueness by design:
var names = nameObjects
.reduce(function(map, nameObject) {
map.set(nameObject.id, nameObject.name);
return map;
}, new Map());
// Look up a name by ID
names.get(47);
// Do something for every name
names.forEach(function(name, key) {
console.info(name, 'has ID', key);
});
Maps are ES6 and you may need a polyfill for some browsers.

Try this worked solution, using push method :
JS :
var arr = {};
for ( var i=0; i < x.length; i++ )
arr[x[i]['name']] = x[i];
var result = new Array();
for ( var key in arr )
result.push(arr[key]);
That will return an array of objects result that contain a non duplicated objects.
Result :
[{
"id": "47",
"name": "chathura"
}, {
"id": "45",
"name": "gayan"
}, {
"id": "48",
"name": "sunimal"
}, {
"id ": "20",
"name ": "yasith "
}, {
"id ": "21 ",
"name ": "thisaru"
}, {
"id ": "42 ",
"name ": "insaf"
}]
Hope this will help.

Related

Comparing 2 objects and making alterations based on Match

I have 2 objects with key-value pairs that should always be identical (match) otherwise I want to modify the value of the key in object #1 to "Some Value - Not available"
Here are my 2 objects:
Object #1
[
{
"name": "John",
"age": "12",
"id": 1
},
{
"name": "tina",
"age": "19",
"id": 2
}]
Object #2 ( name checker)
[
{
"value": "tina"
},
{
"value": "Trevor"
},
{
"value": "Donald"
},
{
"value": "Elon"
},
{
"value": "Pamela"
},
{
"value": "Chris"
},
{
"value": "Jackson"
}
]
I would like to find out if name in Object #1 is found in Object #2 and if it is not found, add " - not available"
e.i
[
{
"name": "John - not available",
"age": "12",
"id": 1
},
{
"name": "tina",
"age": "19",
"id": 2
}
]
Important Note: I'm using ES5 --- not ES6
This should work in ES5
object1.forEach(function(person) {
var found = false;
Object.keys(object2).forEach(function(key) {
if (person.name === object2[key].value) {
found = true;
}
});
if (!found) {
person.name = person.name + " - not available";
}
});

Javascript map is not a function what trying to read data

I am trying to populate a chart so I'm getting the data into 2 lists in order to do this.
This is the data:
var data = [{
"id": "622",
"name": "some name",
"boats": {
"637": {
"id": "637",
"name": " Subcat 1",
"translations": null
},
"638": {
"id": "638",
"name": "Subcat 2",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6286b"
}];
And I am running this code in order to populate the lists:
var chList = [];
var boatList = [];
var boatCount = [];
for (var i = 0; i < data.length; i++) {
var obj = data[i];
var cl = obj.name + " [" + obj.id + "]";
if (obj.boats != null) {
chList.push(cl);
}
if(obj.boats) {
var nme = obj.boats.map( function(item){
return item.name;
});
boatList = boatList.concat(nme);
boatCount.push(nme.length);
}
}
console.log(boatList);
console.log(boatCount);
My problem is that I keep getting:
TypeError: obj.boats.map is not a function
How can I fix this?
Note: The data is actually this:
{
"id": "622",
"name": "some name",
"boats": {
"637": {
"id": "637",
"name": " Subcat 1",
"translations": null
},
"638": {
"id": "638",
"name": "Subcat 2",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6286b"
};
But I added [ and ] to it in order to use data.length and the lists where empty too ... Do I then leave this data as it is?
The problem is that obj.boats is an object, not an array, hence doesn't have the map method.
Try this instead:
Object.keys(obj.boats).map(function(k) { return obj.boats[k].name; });
See MDN
boats is an object, not an array. Map is for arrays.
You could use a for ( in ) loop or Object.keys() to get an array of keys and work with that.
The two other answers are right, I'd change the data though:
"boats": [
{
"id": "637",
"name": " Subcat 1",
"translations": null
},
{
"id": "638",
"name": "Subcat 2",
"translations": null
}
],
Using the id as key and then giving the containing object a "id" property is kinda pointless. When you change the data to this structure your code will work fine.
Besides all other answers that already correctly point to obj.boats being an Object and not an Array, I'd like providing a solution that demonstrates the elegant beauty of Array.reduce ...
var boatChartData = [{
"id": "622",
"name": "some name",
"boats": {
"637": {
"id": "637",
"name": "Subcat 1",
"translations": null
},
"638": {
"id": "638",
"name": "Subcat 2",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6286b"
}, {
"id": "623",
"name": "other name",
"boats": {
"639": {
"id": "639",
"name": "Supercat",
"translations": null
},
"640": {
"id": "640",
"name": "Supercat II",
"translations": null
},
"641": {
"id": "641",
"name": "Supercat III",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6295c"
}];
function collectBoatChartData(collector, chartItem/*, idx, list*/) {
var
boatNameList,
boatMap = chartItem.boats;
if (boatMap != null) {
collector.chartItemTitleList.push([
chartItem.name,
" [",
chartItem.id,
"]"
].join(""));
boatNameList = Object.keys(boatMap).map(collector.getBoatNameByKey, boatMap);
collector.boatNameList = collector.boatNameList.concat(boatNameList);
//collector.chartItemBoatNameList.push(boatNameList);
collector.chartItemBoatCountList.push(boatNameList.length);
}
return collector;
}
var processedBoatChartData = boatChartData.reduce(collectBoatChartData, {
getBoatNameByKey: function (key) {
return this[key].name;
},
boatNameList: [],
chartItemTitleList: [],
//chartItemBoatNameList: [],
chartItemBoatCountList: []
});
console.log("processedBoatChartData.boatNameList : ", processedBoatChartData.boatNameList);
console.log("processedBoatChartData.chartItemTitleList : ", processedBoatChartData.chartItemTitleList);
//console.log("processedBoatChartData.chartItemBoatNameList : ", processedBoatChartData.chartItemBoatNameList);
console.log("processedBoatChartData.chartItemBoatCountList : ", processedBoatChartData.chartItemBoatCountList);
Note
Taking into account the OP's additional comment, mentioning the provided axample's real data structure, the above provided solution of mine just changes to ...
var boatChartData = {
"id": "622",
"name": "some name",
"boats": {
"637": {
"id": "637",
"name": "Subcat 1",
"translations": null
},
"638": {
"id": "638",
"name": "Subcat 2",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6286b"
};
var processedBoatChartData = [boatChartData].reduce(collectBoatChartData, {
getBoatNameByKey: function (key) {
return this[key].name;
},
boatNameList: [],
chartItemTitleList: [],
//chartItemBoatNameList: [],
chartItemBoatCountList: []
});
.., proving that generic solutions can be recycled/adapted easily, if e.g. data structures do change.

Underscore filter array of object using like query

I have the below Json.
{
"results": [
{
"id": "123",
"name": "Some Name"
},
{
"id": "124",
"name": "My Name"
},
{
"id": "125",
"name": "Johnson Johnson"
},
{
"id": "126",
"name": "Mike and Mike"
},
{
"id": "201",
"name": "abc xyz"
},
{
"id": "202",
"name": "abc befd"
},
{
"id": "210",
"name": "jki yuiu"
},
{
"id": "203",
"name": "asdfui uiuu"
},
{
"id": "204",
"name": "sfdhu uiu"
},
{
"id": "205",
"name": "asdfui uyu"
}
]
}
Using Underscore i want to filter the above data using sql like query on id.
for example if pass "2" the json should be filtered and return a new json which contain id starting with 2, If i pass 20 it should return new json with id starting with 20
similar to sql like query and then return n results matching,
correction: I want the data starting with id 2 or whatever parameter i pass i need data starting with it
Try this
function getResult(keyToFilter, valueStartsWith){
return _.filter(results, function(d){ return d[keyToFilter].startsWith(valueStartsWith); })
}
getResult("name", "asdfui");
[{
"id": "203",
"name": "asdfui uiuu"
},
{
"id": "205",
"name": "asdfui uyu"
}]
What about Array.prototype.filter and Array.prototype.slice? (underscore has similar functions but why to use them when it can be solved with plain JS)
function sqlLikeFilter(data, id, maxn) {
return data.result.filter(function(x) { return x.id == id; }).slice(0, maxn);
}
console.log(sqlLikeFilter(yourData, 125, 1));
Try this
function(id){
var result = _.filter(results, function(value) {
return value.id === id
})
return result;
}

Remove duplicate objects, but push property to array on remaining object

I have an array of objects like so:
[
{
"id": "1",
"location": "US"
},
{
"id": "7",
"location": "US"
},
{
"id": "1",
"location": "France"
},
{
"id": "1",
"location": "China"
}
]
I would like to end up with a resulting array that looks like this:
[
{
"id": "1",
"locations": ["US", "France", "China"]
},
{
"id": "7",
"locations": ["US"]
}
]
Is there a solid way to accomplish this using underscore?
I'm contemplating looping through the array and for each id looping through the rest of the array and pushing location values to a locations array on that first object (by id), then at the end removing all duplicate objects (by id) which do not contain a locations property.
This is different from existing questions on SO that simply ask about removing duplicates. I am aiming to remove duplicates while also holding on to certain property values from these duplicates in an array on the 'surviving' object.
Solution in plain Javascript
var data = [{ "id": "9" }, { "id": "1", "location": "US" }, { "id": "7", "location": "US" }, { "id": "1", "location": "France" }, { "id": "1", "location": "China" }],
result = [];
data.forEach(function (a) {
a.location && !result.some(function (b) {
if (a.id === b.id) {
b.locations.push(a.location);
return true;
}
}) && result.push({ id: a.id, locations: [a.location] });
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
You can use reduce function to transform your array.
var data = [
{ "id": "1", "location": "US" },
{ "id": "7", "location": "US" },
{ "id": "1", "location": "France" },
{ "id": "1", "location": "China" }
];
var result = data.reduce(function (prev, item) {
var newItem = prev.find(function(i) {
return i.id === item.id;
});
if (!newItem) {
prev.push({id: item.id, locations: [item.location]});
} else {
newItem.locations.push(item.location);
}
return prev;
}, []);
And a version using underscore:
var result = _.chain(data)
.groupBy('id')
.map(function(group, id){
return {
id: id,
locations: _.pluck(group, 'location')
}
})
.value();

Jquery : transform nested json object to another json object

In javascript/jquery how do i achieve following
old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
Using jquery iterate over the above and change to following
new_dataset = [
{
"dob":"xyz",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
},{
"dob":"er",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
}]
If someone can give the code to transform the data it would help me to understand the iteration
You could do something like:
function transformDataset(oldDataset) {
var newDataset = [];
var newObj;
for (var i = 0; i < oldDataset.length; i++) {
newObj = transformObj(oldDataset[i]);
newDataset.push(newObj);
}
return newDataset;
}
function transformObj(obj) {
var children = obj.children;
obj.name = obj.name.first + ' ' + obj.name.last;
obj.start_date = obj.start_date.month + ' ' + obj.start_date.day + ' ' + obj.start_date.year;
obj.children = [];
for (var i = 0; i < children.length; i++) {
obj.children.push(children[i].child.id);
}
return obj;
}
var new_dataset = transformDataset(old_dataset);
Note that new_dataset will have an array of child id instead of an object with multiple child_id properties.
You also had a typo in old_dataset.start_date.month (was written moth)(or maybe that was intentional).
use map first to iterate the array data (old_dataset), replace element name & start_date with new value then return the array
const old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
let new_dataset = old_dataset.map((arr) => {
arr.name = `${arr.name.first} ${arr.name.last}`
arr.start_date = `${arr.start_date.moth} ${arr.start_date.day} ${arr.start_date.year}`
return arr
})
console.log(new_dataset)

Categories

Resources