I have the following code (using Chrome)
<script>
var arr = [{
"id": 1,
"fn": "bill",
"ln": "blogs"
}, {
"id": 2,
"fn": "jim",
"ln": "jones"
}, {
"id": 3,
"fn": "bill",
"ln": "smith"
}];
var lookFor = "bill";
var result = arr.filter(function(item) {
return if (item.ln == lookFor) return true;
});
alert(result.length);
alert(result[0]["id"] + result[0]["fn"] + result[0]["ln"]);
</script>
I am trying to filter the array and return those that the first name (fn) is bill. Returning id, fn, and ln in a messagebox.
I am probably missing some knowledge of the syntax of this.
Try this
var result = arr.filter(function(item) {
return item.fn === lookFor;
});
....return those that the first name (fn) is bill
But in your code you use item.ln. Also why do you use two return statement
return if (item.ln == lookFor) return true;
You need just return true or false and you can do it like this
return item.fn === lookFor;
if item.fn equals lookFor it will be true, otherwise false
Example
You should be using
var arr = [{
"id": 1,
"fn": "bill",
"ln": "blogs"
}, {
"id": 2,
"fn": "jim",
"ln": "jones"
}, {
"id": 3,
"fn": "bill",
"ln": "smith"
}];
var lookFor = "bill";
var result = arr.filter(function(item) {
return item.ln === lookFor;
});
alert(result.length);
alert(result[0]["id"] + result[0]["fn"] + result[0]["ln"]);
But I guess its not ln which you want, instead you want fn cause their is no ln which is equal to bill.
Related
This function returns diff between two objects , i need to modify it to return common objects. Any help is appreciated.
Array sample:
var array1 = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
}, {
"Name": "Triple",
"URL": "zzz",
"ID": 567
}];
var arrar2 = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
}, {
"Name": "index",
"URL": "zzz",
"ID": 567
}];
// expected result
var resultArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
},
}];
Current code:
function objDiff(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if (origObj.name == destObj.name) return true
})
if (!check) {
destObj.desc = 'missing in source'
resultArray.push(destObj)
}
})
array1.forEach(function(origObj) {
var check = array2.some(function(destObj) {
if (origObj.name == destObj.name) return true
})
if (!check) {
origObj.desc = 'missing in destination'
resultArray.push(origObj)
}
})
return resultArray
}
If all you want is to look for things that are the same in both arrays, you only need to loop over one of them. Something along these lines should work:
function objSame(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if(origObj.name == destObj.name) return true
})
if(check) {
destObj.desc = 'Same in both'
resultArray.push(destObj)
}
})
return resultArray
}
To find array elements that have a common Name property value, you could use a Map to avoid O(n²) time complexity. That map would have the objects from the first array keyed by their name. Pass it as the this object to a filter on the second array:
function objCommon(array1, array2) {
return array2.filter(function (obj) {
return this.has(obj.Name);
}, new Map(array1.map(obj => [obj.Name, obj])));
}
var array1= [
{ "Name": "Single", "URL": "xxx", "ID": 123 },
{ "Name": "Double", "URL": "yyy", "ID": 888},
{ "Name": "Triple", "URL": "zzz", "ID": 567 }];
var array2= [
{ "Name": "Single", "URL": "xxx", "ID": 123 },
{ "Name": "Double", "URL": "yyy", "ID": 888 },
{ "Name": "index", "URL": "zzz", "ID": 567 }];
var result = objCommon(array1, array2);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
That's not your code, but the following function will return all matches by exploring both arrays with two forEach() loops. Algorithm complexity is given by array1.length * array2.length. Don't use for large arrays! But it's the easiest way to think of it. Indeed the first think that comes to my mind is checking every element of array2 for every element of array1 and compare them.
var array1 = ['DETE', 'Ivany', 'James', 'Don', 'Crakcer']
var array2 = ['Jamies', 'Ivanyy', 'DETE', 'Don']
function objMatch(array1,array2) {
var matches = [];
array1.forEach(function(element1) {
array2.forEach(function(element2) {
if(element1 == element2) {
matches.push(element1);
}
});
});
return matches;
}
console.log(objMatch(array1, array2));
// will return ['DETE', 'Don']
Another way to do with only one loop is to use sort(), credit to jeremy
var array1 = ["cat", "sum","fun", "run", "gut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
var arrayMatch = function(array1, array2) {
var matches = [];
array1.sort();
array2.sort();
for (var i = 0; i < array1.length; i += 1) {
if (array2.indexOf(array1[i]) > -1) {
matches.push(array1[i]);
}
}
return matches;
}
console.log(arrayMatch(array1,array2))
And yet another way to do it is by using Array.prototype.filter, credit to Paul S.
var array1 = ['DETE', 'Ivany', 'James', 'Don', 'Crakcer']
var array2 = ['Jamies', 'Ivanyy', 'DETE', 'Don']
function arrayMatch(array1, array2) {
var t;
if (array1.length > array2.length) t = array2, array2 = array1, array1 = t;
return array1.filter(function (e) {
return array2.indexOf(e) > -1;
});
}
console.log(arrayMatch(array1, array2));
I have some data which looks like this:
{
"obj":
[
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
What I need to do is to create 2 arrays from it.
For example:
namelist[];
agelist[];
so the result would be:
namelist: ['name1', 'name2'];
agelist: [24, 17];
My question is, how can I do this?
var namelist = [];
var agelist = [];
for(var i in obj.obj){
namelist.push(obj.obj[i].name);
agelist.push(obj.obj[i].age);
}
console.log(namelist, agelist);
Is this what U wanted ?
var zz={
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
namelist=[];
agelist=[];
zz.obj.forEach(function(rec){
namelist.push(rec.name);
agelist.push(rec.age);
})
console.log(namelist,agelist)
You could use this ES6 code, and use the unitary plus for getting the ages as numbers. Assuming your object is stored in variable data:
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
};
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
console.log(namelist);
console.log(agelist);
var arr = $.map(myObj, function(value, index) {
return [value];
});
console.log(arr);
if you are not using Jquery then:
var arr = Object.keys(myObj).map(function (key)
{ return obj[key];
});`
Make use of jquery map function or otherwise you can loop over the object and push it into array using javascript for loop and use the push() function. Refer Loop through an array in JavaScript
Jquery
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var name = $.map(data.obj, function(value, index) {
return value.name;
});
var age = $.map(data.obj, function(value, index) {
return value.age;
});
console.log(name);
console.log(age);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Javascript
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var names = [], ages=[];
data.obj.forEach(function(value, index) {
names.push(value.name);
ages.push(value.age);
});
console.log(names,ages);
I have this JSON structure:
[{
"name": "ankit",
"DOB": "23/06"
}, {
"name": "kapil",
"DOB": "26/06"
}, {
"name": "ankit",
"DOB": "27/06"
}]
I want to count similar object with value ankit. How can I do this?
You can use Array.prototype.filter():
var count = json.filter(function (el) {
return el.name == 'ankit';
}).length;
How about:
let a = [
{ "name": "ankit", "DOB": "23/06" },
{ "name": "kapil", "DOB": "26/06" },
{ "name": "ankit", "DOB": "27/06" }
];
let count = 0;
a.forEach(item => {
if (item.name === "ankit") {
count++;
}
});
(code in playground)
You could use an object for counting and get the wanted count for a name with the name as property.
var data = [{ "name": "ankit", "DOB": "23/06" }, { "name": "kapil", "DOB": "26/06" }, { "name": "ankit", "DOB": "27/06" }],
count = {};
data.forEach(function (a) {
count[a.name] = (count[a.name] || 0) + 1;
});
console.log(count);
console.log(count['ankit']);
You can use the reduce method to reduce the items that have the name ankit to a number.
var items = [
{
name: 'ankit',
DOB: '23/06'
},
{
name: 'kapil',
DOB: '26/06'
},
{
name: 'ankit',
DOB: '27/06'
}
]
var numItems = items.reduce(function (count, item) {
return item.name === 'ankit' ? count + 1 : count
}, 0)
document.write('Number of items with the name `ankit`: ' + numItems)
1. Get the object from JSON:
var obj = JSON.parse(text);
2. Get your array filtered:
var count = obj.filter(function(obj) { return obj.name == "ankit" }).length;
Say i have an array with several objects, looking like this:
{
"firstname": John,
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}],
}, ...
How do i loop through these objects while also looping through their "numbers" property?
var input = {
"firstname": "John",
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}]
}
for (var key in input) {
if (key === "numbers") {
for (var i=0; i < input[key].length; i++) {
console.log(input[key][i]);
}
} else {
console.log(key + ":" + input[key])
}
}
Nested loop:
var input = [{
"firstname": John,
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}],
}]
input.forEach(function(item) {
item.numbers.forEach(function(number) {
console.log(number.id, number.value)
}
}
This one uses recursion so it will work even if the pattern isn't the same:
function looopAllTheThings(theThings, theCallback, depth){
if(undefined===depth) depth = 0;
if(typeof theThings == "object"){
for(var p in theThings)
if(theThings.hasOwnProperty(p))
if("object" == typeof theThings[p] ||
"array" == typeof theThings[p])
looopAllTheThings(theThings[p], theCallback, (depth+1));
else theCallback(p, theThings[p], depth);
}else if(typeof theThings == "array"){
for(var i=0; i<theThings.length; i++)
if("object" == typeof theThings[i] ||
"array" == typeof theThings[i])
looopAllTheThings(theThings[i], theCallback, (depth+1));
else theCallback(p, theThings[i], depth);
}else{
theCallback(null, theThings, depth);
}
}
Use it like this:
looopAllTheThings(data, function(key, value, depth){
document.getElementById('out').innerHTML += ("-".repeat(depth))+" "+key+" = "+value+"<br>";
});
Here's a fiddle: https://jsfiddle.net/2o2Lyayj/
http://jsfiddle.net/rw0z9e2j/
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
var arr = [],
tempObj = {};
$.each(sports, function (i, obj) {
var sport_id = obj.id;
$.each(playersData, function (i, obj) {
if (sport_id == obj.sport_id) {
tempObj = {
"sport_id": obj.sport_id,
"id": obj.id,
"name": obj.name
};
arr.push(tempObj);
}
});
obj.players = arr;
});
console.log(sports);
I try to build an array of players and put them within sports group according to sport_id but above logic has failed. It didn't group properly, the player who's in sport_id = 1 should go to sport which its id = 1 but why it didn't?
what's wrong with above loop there?
I suppose this is what you want:
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
sports.forEach(function (a) {
var arr = [];
playersData.forEach(function (b) {
if (a.id == b.sport_id) {
arr.push(b);
}
});
a.players = arr;
});
document.write('<pre>' + JSON.stringify(sports, 0, 4) + '</pre>');
You're declaring your temp vars outside of your loops, these should be scoped to your loops and thrown away after each operation.
var arr = [],
tempObj = {};
http://jsfiddle.net/samternent/rw0z9e2j/2/
You have to put it after push:
arr.push(tempObj);
obj.players = arr;
Actually you need this:
var sports = [{
"id": 1,
"name": "baseball"
}, {
"id": 2,
"name": "Football"
}];
var playersData = [{
"sport_id": 2,
"id": "nv12",
"name": "James"
}, {
"sport_id": 2,
"id": "nv11",
"name": "Jean"
}];
var arr = [];
$.each(sports, function (i, obj) {
$.each(playersData, function (i, player) {
if (obj.id === player.sport_id) {
var tempObj = {
"sport_id": player.sport_id,
"id": player.id,
"name": player.name
};
arr.push(tempObj);
obj.players = arr;
}
});
});
console.log(sports);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope you want to put inside the Sports group, but you are adding inside the player array, please notice, so please call
obj.sports = arr;
Hope it solve your problem .