Compare two arrays having objects and remove duplicates from first array - javascript

I have two arrays that contain objects. From first array how can I remove the items that are already present in the second array?
First array:
var s = [
{"Name": "1"},
{"Name": "2"},
{"Name": "3"},
{"Name": "4"},
{"Name": "5"},
{"Name": "6"}
]
Second array:
var t = [
{"Name": "1"},
{"Name": "2"},
{"Name": "3"},
{"Name": "8"}
]
Expected output:
[
{"Name": "4"},
{"Name": "5"},
{"Name": "6"}
]

You can use filter() along with some()
var s = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"4"},{"Name":"5"},{"Name":"6"}];
var t = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"8"}];
result = s.filter(a => !t.some(b => a.Name === b.Name));
console.log(result);

An approach using set and .filter method
var s=[
{
"Name": "1"
},
{
"Name": "2"
},
{
"Name": "3"
},
{
"Name": "4"
},
{
"Name": "5"
},
{
"Name": "6"
}
];
var t= [
{
"Name": "1"
},
{
"Name": "2"
},
{
"Name": "3"
},{
"Name": "8"
}
];
var set = new Set();
t.forEach(obj => set.add(obj.Name));
s=s.filter(obj => !set.has(obj.Name))
console.log(s);

z = f(s, t);
function f(first, second) {
var z = [];
for (var i = 0; i < first.length; i++) {
var included = false;
for (let j = 0; j < second.length; j++) {
if(equal(first[i], second[j]))
included = true;
//break; //optional
}
if(!included)
z.push(first[i]);
}
return z;
}
function equal(a,b){
//however you define the objs to be equal
return a.Name == b.Name;
}

Related

Creating dynamic data coming from multiple queries for SunBurst graph

I'm working on SunBurst graph using d3 for my project. I'm able to render it. The problem is for SunBurst we always have pass data in a certain format to make it work.
I have a code that takes 4 query data and merges into one. But this is very specific to 1 graph. I want it to be dynamic so that I can interchange their order.
Note: The last data should always hold name and count keys.
function createpayload(name, count){
var x = {
name: name,
count: count,
children: []
}
return x
}
function createpayloads(name, count){
var x = {
name: name,
count: count
}
return x
}
function createPayload(projectType, subProject, status, assignedTo){
var payload = {
name:"My Project",
children:[]
}
payload.children = projectType
payload.children.forEach(element => {
element.children = []
subProject.forEach(val => {
if(element.name == val.projecttype){
element.children.push(createpayload(val.name))
}
})
element.children.forEach((item) => {
status.forEach(valst => {
if(element.name == valst.projecttype && item.name == valst.subproject){
item.children.push(createpayload(valst.name))
}
})
item.children.forEach((items) => {
assignedTo.forEach(valss => {
if(element.name == valss.projecttype && item.name == valss.subproject && items.name == valss.status){
items.children.push(createpayloads(valss.name, valss.count))
}
})
})
})
})
return payload
}
Here this code works but the number of inputs it takes is fixed to 4((projectType, subProject, status, assignedTo). I want this to accept any number of parameter in any order. But if I change the order how to make this dynamic enough to get the desired output?
This the the structure d3 SunBurst Accepts
var nodeData = {
"name": "TOPICS", "children": [{
"name": "Topic A",
"children": [{"name": "Sub A1", "size": 4}, {"name": "Sub A2", "size": 4}]
}, {
"name": "Topic B",
"children": [{"name": "Sub B1", "size": 3}, {"name": "Sub B2", "size": 3}, {
"name": "Sub B3", "size": 3}]
}, {
"name": "Topic C",
"children": [{"name": "Sub A1", "size": 4}, {"name": "Sub A2", "size": 4}]
}]
};

How to make a JSON object out of a dictionary?

I'me new to JavaScript. In the browser I receive a long dictionary like this:
{"cat": "4" , "dog": "5", "fish": "9" }
I'm wondering what is the most efficient way to convert it to a JSON object like:
[
{
"name": "cat",
"value": "4"
},
{
"name": "dog",
"value": "5"
},
{
"name": "fish",
"value": "9"
}
]
You can Loop through it and push each key-value-pair to an Array.
var tValue = {"cat": "4" , "dog": "5", "fish": "9" };
var tList = [];
for(var tKey in tValue) tList.push({name: tKey, value: tValue[tKey]});
console.log(tList);
You can just loop over the dictionary object keys using Object.keys() method, and use .map() method to transform each iterated key/value pair to the appropriate object:
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
Demo:
var obj = {
"cat": "4",
"dog": "5",
"fish": "9"
};
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
console.log(results);
You can use the function Object.entries to get every key-value pairs and with the function map build the desired output.
let obj = {"cat": "4" , "dog": "5", "fish": "9" },
result = Object.entries(obj).map(([name, value]) => ({name, value}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this by this way :
Call a for in loop and read your first object
Push the name and the value in your new object one by one..
Sample code :
var a = {"cat": "4" , "dog": "5", "fish": "9" };
var newJSON = [] ;
console.log(a);
for ( key in a ) {
newJSON.push({name : key, value : a[key]});
}
console.log(newJSON);
You can have this kind of formatted object
{
animals : [
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]
}
or like this
[
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]

check if record exists in javascript object

I have a web app which passes delimited fields to another web page. It works fine! But... I want to list the fields (Name) that don't exist in the javascript object. How can this be accomplished?
JS object:
var members = [ { "Class": "E", "Rating": "1000", "ID": "16720664", "Name": "Adeyemon, Murie", "Expires": "1000.10.10" },
{ "Class": "B", "Rating": "1735", "ID": "12537964", "Name": "Ahmed, Jamshed", "Expires": "2018.10.18" },
{ "Class": "C", "Rating": "1535", "ID": "12210580", "Name": "Attaya, James", "Expires": "2019.01.12" },
{ "Class": "F", "Rating": "0001", "ID": "16281977", "Name": "Auld, Thomas", "Expires": "1000.10.10" },
{ "Class": "B", "Rating": "1793", "ID": "10117780", "Name": "Badamo, Anthony", "Expires": "2018.09.12" }
]
JS CODE:
let dataString = "Adeyemon, Murie|Ahmed, Jamshed|Attaya, James|Badamo, Anthony|Birmingham, Gerald|";
let splitString = dataString.split("|");
for (let i = 0; i < splitString.length; i++) {
$temp = splitString[i - 1];
if ($temp > "") {
members.find(x => x.Name === $temp);
}
}
use filter
var dataString =
'Adeyemon, Murie|Ahmed, Jamshed|Attaya, James|Badamo, Anthony|Birmingham, Gerald|'
var members = [{"Class":"E","Rating":"1000","ID":"16720664","Name":"Adeyemon, Murie","Expires":"1000.10.10"},{"Class":"B","Rating":"1735","ID":"12537964","Name":"Ahmed, Jamshed","Expires":"2018.10.18"},{"Class":"C","Rating":"1535","ID":"12210580","Name":"Attaya, James","Expires":"2019.01.12"},{"Class":"F","Rating":"0001","ID":"16281977","Name":"Auld, Thomas","Expires":"1000.10.10"},{"Class":"B","Rating":"1793","ID":"10117780","Name":"Badamo, Anthony","Expires":"2018.09.12"}]
var res = dataString.split('|').filter(
name => !members.map(o => o.Name).find(n => n === name)
).filter(name=>name.trim()!=='')
console.log(res);
You can first create Name to object mapping and then search name from string in this object/map which will cost O(n) for n names.
var members = [ { "Class": "E", "Rating": "1000", "ID": "16720664", "Name": "Adeyemon, Murie", "Expires": "1000.10.10" },
{ "Class": "B", "Rating": "1735", "ID": "12537964", "Name": "Ahmed, Jamshed", "Expires": "2018.10.18" },
{ "Class": "C", "Rating": "1535", "ID": "12210580", "Name": "Attaya, James", "Expires": "2019.01.12" },
{ "Class": "F", "Rating": "0001", "ID": "16281977", "Name": "Auld, Thomas", "Expires": "1000.10.10" },
{ "Class": "B", "Rating": "1793", "ID": "10117780", "Name": "Badamo, Anthony", "Expires": "2018.09.12" }
];
var nameMap = members.reduce((prev, next) => {
prev[next.Name] = next;
return prev;
}, {});
let dataString = "Adeyemon, Murie|Ahmed, Jamshed|Attaya, James|Badamo, Anthony|Birmingham, Gerald|";
let names = dataString.split("|");
let result = names.filter(name => name && !(name in nameMap));
console.log(result);
Try reducing the members array to a Set of names. Then you can filter your splitString array using Set.prototype.has()
const members = [{"Class":"E","Rating":"1000","ID":"16720664","Name":"Adeyemon, Murie","Expires":"1000.10.10"},{"Class":"B","Rating":"1735","ID":"12537964","Name":"Ahmed, Jamshed","Expires":"2018.10.18"},{"Class":"C","Rating":"1535","ID":"12210580","Name":"Attaya, James","Expires":"2019.01.12"},{"Class":"F","Rating":"0001","ID":"16281977","Name":"Auld, Thomas","Expires":"1000.10.10"},{"Class":"B","Rating":"1793","ID":"10117780","Name":"Badamo, Anthony","Expires":"2018.09.12"}]
const dataString = "Adeyemon, Murie|Ahmed, Jamshed|Attaya, James|Badamo, Anthony|Birmingham, Gerald|";
const names = members.reduce((c, {Name}) => c.add(Name), new Set())
const missing = dataString.split('|')
.filter(name => name.trim() && !names.has(name))
.join('; ') // output from your comment on another answer
console.info(missing)
I've added in the name.trim() to filter out the empty record created by the trailing | in your dataString.
The reason for creating a Set is to avoid searching the entire members array for each name in dataString. Set.prototype.has() should be O(1)

Devide player into two team by their ratings in angularjs / Javascript

I have an array of players with player name and ratings.
$scope.players = [
{"name": "Qasim", "rating": "10"},
{"name": "Mahsam", "rating": 10},
{"name": "Aj", "rating": 3},
{"name": "Osman", "rating": 7},
{"name": "Usama", "rating": 7},
{"name": "Bilal", "rating": 3}
]
I need to divide players into two team based on their ratings.
var playerLength = $scope.players.length,
grouped = _.groupBy($scope.players,function(item){return item.rating});
I want to divide players in two team with equal ratting in two balanced teams.
Here is a way to make your teams. I loop over all the players and push the player in the weakest team.
Here is a JSFiddle demo, more readable than the snippet.
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.players = [{
"name": "Qasim",
"rating": 10
}, {
"name": "Mahsam",
"rating": 10
}, {
"name": "Aj",
"rating": 3
}, {
"name": "Osman",
"rating": 7
}, {
"name": "Usama",
"rating": 7
}, {
"name": "Bilal",
"rating": 3
}];
$scope.team1 = [];
$scope.team2 = [];
$scope.createTeams = function() {
angular.forEach($scope.players, function(player) {
if ($scope.teamStrength($scope.team1) < $scope.teamStrength($scope.team2)) {
$scope.team1.push(player);
} else {
$scope.team2.push(player);
}
});
}
$scope.teamStrength = function(team) {
var sum = 0;
if(team.length == 0) return 0;
for(var i = 0; i < team.length; i++) {
sum += team[i].rating;
}
return sum;
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<button ng-click="createTeams()">Create teams!</button>
<h1>Team 1</h1>
<div ng-repeat="p in team1">
{{p.name}} ({{p.rating}})
</div>
<h1>Team 2</h1>
<div ng-repeat="p in team2">
{{p.name}} ({{p.rating}})
</div>
</div>
</div>
var playerArr = {};
var rateArr = []
var leftTeam = [];
var rightTeam = [];
for(id in $scope.players){
playerArr[$scope.players[id].rating] = $scope.players[id];
rateArr.push($scope.players[id].rating);
}
rateArr.sort();
for(i = 0; i < rateArr.length; i+=2) {
leftTeam.push({name:playerArr[rateArr[id]].name, rating: playerArr[rateArr[id]].rating});
}
for(i = 1; i<rateArr.length; i+=2){
rightTeam.push({name.playerArr[rateArr[id]].name, rating: playerArr[rateArr[id]].rating;
}
A way to do it:
UPDATE: Change has been made to match the question.
var footballers = [
{"name": "Qasim", "rating": "10"},
{"name": "Mahsam", "rating": 10},
{"name": "Aj", "rating": 3},
{"name": "Osman", "rating": 7},
{"name": "Usama", "rating": 7},
{"name": "Bilal", "rating": 3}
];
footballers.sort(function(a, b){
return a.rating - b.rating
});
console.log(footballers); //sorted
var team1 = [], team2 = [];
//Assuming, footballers have the same rating twice
for (let index=0;index<footballers.length;index += 2) {
team1.push(footballers[index]);
team2.push(footballers[index+1]);
}
console.log(team1, team2);
:)

Deleting a row from javascript object

I have a javascript object which looks like this :-
var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
Now , I have to delete all the rows in the object with id value 2. How can this be done ?
If you don't need the original array after "deleting" rows, you can use splice like this:
http://jsfiddle.net/rmcu5/1/
var myArray = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
function removeItemsById(arr, id) {
var i = arr.length;
if (i) { // (not 0)
while (--i) {
var cur = arr[i];
if (cur.id == id) {
arr.splice(i, 1);
}
}
}
}
removeItemsById(myArray, "2");
console.log(JSON.stringify(myArray));
It doesn't create a new array, just modifies the original in place. If you need the original array and all of its items, then use one of the other solutions that return you a modified copy of the original.
Note that what you call myObject is actually an array therefore you can use array methods on it:
myObject = myObject.filter(function( obj ) {
return obj.id != 2;
});
Demo: http://jsfiddle.net/elclanrs/LXpYj/
try this:
function deleteObject(array,id)
{
var newObject=[];
for (var o in array) {
if(array[o].id!=id)
newObject.push(array[o]);
}
return newObject;
}
working JS fiddle
You can do without creating new array, you need to write remove function:
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
Without New Array Delete Object
try it with filter (its an array not a object)
var rr = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"}, {"id": "2", "URL": "http://shsusadhf.com", "value": "2"}, {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
rr = rr.filter(function(e) {
return e.id != 2;
});
Here you go, this is without recreating the array or anything.
var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
for(i=0,iMax=myObject.length;i<iMax;i++){
(function (a) {
if(this.id=="2"){
delete myObject[a];
}
}).call(myObject[i],i);
}
console.log(myObject);
​
​
jsFiddle
http://jsfiddle.net/gG2zz/1/

Categories