Create an array based on same Id in javascript - javascript

This an example request object.
"stories": [
{
"ID": "1",
"TRADER_ID": "38",
"IMAGE": ""
},
{
"ID": "2",
"TRADER_ID": "38",
"IMAGE": ""
},
{
"ID": "3",
"TRADER_ID": "40",
"IMAGE": ""
},
{
"ID": "4",
"TRADER_ID": "40",
"IMAGE": ""
},]
like this i will be having list of story, I want create an array based on same TRADER_ID. because i need to add an image slide slider, for unique Traader Id i can get the image url

This is madness I know, but works. If anyone is able to simplify it, please do it :P
OP wrote: "i need output like ["38", "38"] ["40", "40"]"
var stories = [{
"ID": "1",
"TRADER_ID": "38"
}, {
"ID": "2",
"TRADER_ID": "38"
}, {
"ID": "3",
"TRADER_ID": "40"
}, {
"ID": "4",
"TRADER_ID": "40"
}];
(function change(array) {
var ids = [];
stories.forEach(v => ids.push(v.TRADER_ID));
var sortedArr = [...new Set(Array.from(ids))];
var newOne = [];
var times = 0;
var obj = {};
var result = [];
var cb = [];
for (var i = 0; i < sortedArr.length; i++) {
for (var j = 0; j < stories.length; j++) {
if (stories[j].TRADER_ID == sortedArr[i]) {
times++;
}
}
obj.prop = sortedArr[i];
obj.times = times;
newOne.push(obj);
obj = {};
times = 0;
}
for (var k = 0; k < newOne.length; k++) {
for (var l = 0; l < newOne[k].times; l++) {
cb.push(newOne[k].prop);
}
result.push(cb);
cb = [];
}
console.log(result);
})(stories);

You can use the ID as the index of array and the TRADER_ID as number and make a sort or find the element by numbres (TRADER_ID)

Related

Update array objects with a single array in JavaScript

I'm having difficulty updating object values from a separate array.
Example:
mainArray = [
{ "name": "bob", "complete": "25" },
{ "name": "john", "complete": "50" },
{ "name": "mike", "complete": "75" },
];
colorArray = ["#ff0000", "#00ff00", "#0000ff"];
I need to create a new Array that combines these values.
for (i = 0, ilen = mainArray.length; ilen > i; i++) {
newArray.push({
name: mainArray[i].name,
complete: mainArray[i].complete,
color: '',
});
}
No matter what I do, I either only get #0000ff back or can't get anything working at all. Failed attempt:
for (j = 0, jlen = newArray.length; jlen > j; j++) {
for (k = 0, km = colorArray.length; km > k; k++) {
newArray[j].color = colorArray[k];
}
}
Goal is to get back:
newArray = [
{ "name": "bob", "complete": "25", "color": "#ff0000" },
{ "name": "john", "complete": "50", "color": "#00ff00" },
{ "name": "mike", "complete": "75", "color": "#0000ff" }
];
What is the correct way to do this?
Just set the color key of each person based on the index of the colorArray.
var mainArray = [
{ "name": "bob", "complete": "25" },
{ "name": "john", "complete": "50" },
{ "name": "mike", "complete": "75" },
];
var colorArray = ["#ff0000", "#00ff00", "#0000ff"];
var newArray = [];
for (var i = 0; i < mainArray.length; i++) {
newArray.push({
name: mainArray[i].name,
complete: mainArray[i].complete,
color: colorArray[i]
});
}
A more functional approach using Array.map and Object.assign looks like
var mainArray = [
{ "name": "bob", "complete": "25" },
{ "name": "john", "complete": "50" },
{ "name": "mike", "complete": "75" },
];
var colorArray = ["#ff0000", "#00ff00", "#0000ff"];
var newArray = mainArray.map((x, i) =>
Object.assign({}, x, {color: colorArray[i]})
)
console.log(newArray);
You have an unnecessary nested loop below:
for (j = 0, jlen = newArray.length; jlen > j; j++) {
for (k = 0, km = colorArray.length; km > k; k++) {
newArray[j].color = colorArray[k];
}
}
You may change it to :
for (j = 0, jlen = newArray.length; jlen > j; j++) {
newArray[j].color = colorArray[j];
}

JSON.parse(data) return [undefine]

data = {
"users": [
[{
"value": "01",
"text": "ABC XYZ"
}],
[{
"value": "02",
"text": "XYZ ABC"
}]
]
}
var jsonData = JSON.parse(data);
for (var i = 0; i < jsonData.users.length; i++) {
var userlist = jsonData.users[i];
alert(userlist.text)
}
This output: [undefine];
But i want to get [ABC XYZ] and [XYZ ABC].
So how can I get text or value from this array?
data is already a JavaScript object, so no need for the extra JSON.parse.
You are getting an undefined result because users is an array of arrays, rather than an array of objects.
Try accessing the userlist like this:
var userlist = data.users[0][i];
JSBin: https://jsbin.com/sifoyivayi/edit?html,js,output
Your object contains nested array. Try like following.
var data = { "users": [[{ "value": "01", "text": "ABC XYZ" }], [{ "value": "02", "text": "XYZ ABC" }]] };
for (var i = 0; i < data.users.length; i++) {
var userlist = data.users[i][0];
alert(userlist.text);
}
Try like this:
var data={"users":[[{"value":"01","text":"ABC XYZ"}],[{"value":"02","text":"XYZ ABC"}]]};
for (var i = 0; i < data.users.length; i++) {
var userlist = data.users[0][i];
alert(userlist.text);
}

Many to Many mapping objects in javascript

Am having two sets of arrays :
$scope.selectedEmployees = ["1001", "1002"];
$scope.selectedTasks = ["Task1", "Task2"];
I wanted to generate an array of objects by combining the employees and tasks like a many to many relationship.The length of $scope.selectedEmployees and $scope.selectedTasks may vary :
newArray=[
{
"empId": 1001,
"task": "Task1"
},
{
"empId": 1001,
"task": "Task2"
},
{
"empId": 1002,
"task": "Task2"
},
{
"empId": 1002,
"task": "Task2"
}
]
The method I tried:
var newArray=[];
for (var i = 0; i <$scope.selectedEmployees.length; i++) {
for (var j = 0; j <$scope.selectedTasks .length; j++) {
newArray.push({"empId":$scope.selectedEmployees[i],
"task":$scope.selectedIntervention[j]
})
}
}
But i'm not able to get the required format.Any help will be grateful.
http://jsfiddle.net/zuv8y9wk/
Also instead of selectedTasks, selectedIntervention was used
var $scope = {};
$scope.selectedEmployees = ["1001", "1002"];
$scope.selectedTasks = ["Task1", "Task2"];
var newArray = [];
for (var i = 0; i < $scope.selectedEmployees.length; i++) {
for (var j = 0; j < $scope.selectedTasks.length; j++) {
newArray.push({
"empId": $scope.selectedEmployees[i],
"task": $scope.selectedTasks[j]
})
}
}
console.log(newArray)

Compare two objects in jQuery and get the difference [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 7 years ago.
Using jQuery I would like to compare 2 objects:
sourceArray:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
destination array
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
What I would like to do, is compare the target object with the source object based on the ID and find the mis-matched entries with a description on the resultant object. So the result will look like this:
var resultArray = [{
"Name": "Double",
"URL": "yyy",
"ID": 888,
"desc": "missing in source"
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345,
"desc": "missing in destination"
}];
Any quick help is really appreciated.
This isn't a good use of jQuery, but here is some vanilla javascript that does what you want.
function objDiff(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
destObj.desc = 'missing in source'
resultArray.push(destObj)
}
})
array1.forEach(function(origObj) {
var check = array2.some(function(destObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
origObj.desc = 'missing in destination'
resultArray.push(origObj)
}
})
return resultArray
}
https://jsfiddle.net/9gaxsLbz/1/
If you are wanting to dedupe your array, this will work:
var merged = origArray.concat(destArray);
var unique = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? false : this.push(item.ID);
}, []);
Fiddle: https://jsfiddle.net/Ljzor9c6/
If you are only wanting items that were duped, you can easily invert the condition:
var merged = origArray.concat(destArray);
var dupes = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? true : !this.push(item.ID);
}, []);
You can loop through the items in the first array and put the ID's in a map, then loop through the items in the second array and remove the matching ID's and add the missing.
Then just loop through the map to create the objects in the resulting array:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var map = {};
for (var i = 0; i < origArray.length; i++) {
map[origArray[i].ID] = 'source';
}
for (var i = 0; i < destArray.length; i++) {
var id = destArray[i].ID;
if (id in map) {
delete map[id];
} else {
map[id] = 'destination';
}
}
var resultArray = [];
for (key in map) {
var arr = map[key] == 'source' ? origArray : destArray;
for (var i = 0; arr[i].ID != key; i++) ;
resultArray.push({
Name: arr[i].Name,
URL: arr[i].URL,
ID: arr[i].ID,
desc: 'missing in ' + map[key]
});
}
// show result in StackOverflow snippet
document.write(JSON.stringify(resultArray));
var result = [];
for(var i = 0; i < oa.length; i++) {
var idx = mIndexOf(oa[i].ID);
if(idx > -1) {
oa.splice(i, 1);
da.splice(idx, 1);
}
}
for(var i = 0; i < oa.length; i++) {
var ln = result.length;
result[ln] = oa[i];
result[ln].desc = "missing in destination";
}
for(var i = 0; i < da.length; i++) {
var ln = result.length;
result[ln] = da[i];
result[ln].desc = "missing in origin";
}
function mIndexOf(id) {
for(var i = 0; i < oa.length; i++)
if(oa[i].ID == id)
return i;
return -1;
}
console.log(result);
0: Object
ID: 345
Name: "Double"
URL: "yyy"
desc: "missing in destination"
1: Object
ID: 888
Name: "Double"
URL: "yyy"
desc: "missing in origin"
jsfiddle DEMO
For things like this, you should use lodash. With lodash you can just do this:
var resultArray = _.defaults(destArray, origArray);

Javascript: How to get object from object in an array

Sample data:
{
"data": [
{
"name": {
"full": "JOHN",
"rank": "SENIOR"
},
"mobile": "12345"
},
{
"name": {
"full": "HENRY",
"rank": "SENIOR"
},
"mobile": "67890"
},
{
"name": {
"full": "SAM",
"rank": "JUNIOR"
},
"mobile": "54321"
}
]
}
i'm trying to get the total number of senior members from the data sample above, and i can get the data.name and data.mobile, but i can't get the 'rank' data from the parent 'name' object. can anyone please guide me to obtain the rank data. below is my javascript:
function countRank(rank) {
var i;
for (i in rank.data) {
if (rank.data[i] == "SENIOR") {
i++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + i;
}
}
<div id="senior"></div>
Try this JSFIDDLE
function countRank(rank) {
var k=0;
for (var i=0; i< rank.data.length; i++) {
if (rank.data[i].name.rank == "SENIOR") {
k++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + k;
}
}
countRank(rank);
You can make something like this
var rank = {
"data": [{
"name": {
"full": "JOHN",
"rank": "SENIOR"
},
"mobile": "12345"
}, {
"name": {
"full": "HENRY",
"rank": "SENIOR"
},
"mobile": "67890"
}, {
"name": {
"full": "SAM",
"rank": "JUNIOR"
},
"mobile": "54321"
}]
};
function countRank(rank) {
var i = 0,
arr = rank.data;
for (var j = 0; j < arr.length; j++) {
for (var prop in arr[j]) {
if (arr[j][prop].rank == "SENIOR") {
i++;
}
document.getElementById('senior').innerHTML = 'Total senior members: ' + i;
}
}
}
countRank(rank);
myObject.data[0].name.rank
>>> "SENIOR"
Assuming that whole object is called obj:
var i=0;
for (i=0; i < obj.data.length; i++) {
console.log(obj.data[i].name.rank);
}
function countRank(rank) {
var count = 0;
var arr = rank.data;
for (var i=0; i<arr.length; i++) {
var name = arr[i].name;
if (name.rank == "SENIOR") {
count++;
}
}
alert(count);
}
I checked it and it worked well.
Using jQuery you can find rank from above data easily.
checkout sample on jsFiddle
http://jsfiddle.net/uBnfu/
$.each(jsonData.data, function (index, value) {
alert(value.name['rank']);
});

Categories

Resources