I have response JSON object which has a series array of objects like this:
{
series: [
{
name: 'a',
data: [1,2,3]
},
{
name: 'b',
data: [4,5,6]
}
]
}
What I want is to retrieve the data values corresponding to the name value.
So far I have come to this:
$scope.nameArr[i] = response.series[i].name;
which is giving me correct name array but for the corresponding data value my below code is failing
for(var i=0; i<response.series.length; i++) {
$scope.nameArr[i] = response.series[i].name;
for (var j=0; j<response.series[i].data.length; j++){
$scope.dataArr[j] = response.series[i].data[j];
}
}
You could use array.filter to get the data by name.
The for loop would also work and you don't need the nested loop for this.
I would prefer the filter because it's easier to read but the for-loop is probably a bit faster in execution time.
Please have a look at the demo below or in this fiddle.
var response = {
series: [{
name: 'a',
data: [1, 2, 3]
}, {
name: 'b',
data: [4, 5, 6]
}]
};
function getDataByName(name) {
return response.series.filter(function(item, index) {
console.log(item);
return (item.name == name);
});
}
var filtered = getDataByName('a');
console.log(filtered[0].data);
$('#result').append('with filter: ' + JSON.stringify(filtered[0].data) + '<br/>');
var item, series = [];
var queryByName = 'a';
for (var i = 0; i < response.series.length; i++) {
item = response.series[i];
if (item.name == queryByName) {
series.push(item);
}
}
$('#result').append('with for loop: ' + JSON.stringify(series[0].data));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Try this:
angular.forEach(series,function(item,index){
$scope.nameArr.push(item.name);
$scope.dataArr.push(item.data);
})
Javascript solution, just change the way you do the foreach loop to
angular.forEach(array, function(item)....etc
Here:
var x = {
series: [
{
name: 'a',
data: [1,2,3]
},
{
name: 'b',
data: [4,5,6]
}
]
}
var results = [];
x.series.forEach(function(item) {
item.data.forEach(function(subitem) {
results.push(subitem);
})
});
console.log(results)
https://jsfiddle.net/6worooos/1/
Related
I want to get all the values that equal a certain number and count how many of each of the objects.
My code looks like this:
var countItems = {
"aa":"70",
"bb":"70",
"cc":"80",
"dd":"90",
"ee":"90",
"ff":"90"
}
Now what I want to do is count each on that is in the second half.
For example, there are two "70", one "80", and three 90. Then I can assign to variables:
var firstCounter = ?? // 2
var secondCounter = ?? // 1
var thirdCounter = ?? // 3
?? is I don't know what goes here.
If it was structed differently like the following, I could do it like this:
let firstCounter = 0;
for (let i = 0; i < countItems.length; i++) {
if (countItems[i].status === '70') firstCounter++;
}
let secondCounter = 0;
for (let i = 0; i < countItems.length; i++) {
if (countItems[i].status === '80') secondCounter++;
}
let thirdCounter = 0;
for (let i = 0; i < countItems.length; i++) {
if (countItems[i].status === '90') thirdCounter++;
}
But the thing is, my original code which is what I have is not structured like that, so I'm not sure how to adapt it.
How can I count the items in the original list (var countItems) so that I can find out how much each value is?
You could use Object.values(countItems) to get an array that looks like this: ["70","70","80","90","90","90"] then either use a for loop to conditionally increment whatever counters you want, or use something like Array.reduce or Array.filter to count the elements you need.
You could use reduce to create a counted hash map like so:
const countItems = [
{ data: 'aa', status: '70' },
{ data: 'bb', status: '70' },
{ data: 'cc', status: '80' },
{ data: 'dd', status: '90' },
{ data: 'ee', status: '90' },
{ data: 'ff', status: '90' },
];
const countedHash = countItems.reduce((acc, curr) => {
if (!acc[curr.status])
acc[curr.status] = 1
else
acc[curr.status] += 1
return acc
}, {})
/* print out the results */
console.log(countedHash)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You can access object keys like this :
countItems["aa"] // it will return "70"
You can also loop on the object (if you want to do as you did in your example) :
for (const item in countItems) {
console.log(countItems[item])
if (countItems[item] == "70") firstCounter++;
}
Object.values() and reduce() are both the right ideas. Taken together...
var countItems = {
"aa":"70",
"bb":"70",
"cc":"80",
"dd":"90",
"ee":"90",
"ff":"90"
};
let counts = Object.values(countItems).reduce((acc, value) => {
if (!acc[value]) acc[value] = 0;
acc[value]++;
return acc;
}, {});
let [theFirstValue, theSecondValue, theThirdValue] = Object.values(counts)
console.log(theFirstValue, theSecondValue, theThirdValue);
const countItems = [
{ data: 'aa', status: '70' },
{ data: 'bb', status: '70' },
{ data: 'cc', status: '80' },
{ data: 'dd', status: '90' },
{ data: 'ee', status: '90' },
{ data: 'ff', status: '90' },
];
var countValues = Object.values(countItems);
let obj ={}
for(let val of countValues){
if(!obj[val.status]){
obj[val.status] = 1
}else{
obj[val.status] += 1
}
}
console.log(obj)
I have as a result from an input form a couple of strings and I want them to convert them, so they fit as data for my ajax-request. I am looking for an easy way, but I can't get it right. Basically I want to convert/map this array:
[
{ name: "[1][apples]", value: "2" }
{ name: "[1][melons]", value: "1" }
{ name: "[2][apples]", value: "2" }
{ name: "[2][melons]", value: "4" }
{ name: "[3][apples]", value: "3" }
{ name: "[3][melons]", value: "2" }
]
into
[{"id": 1, "apples": 2, "melons": 1}, {"id": 2, "apples": 2, "melons": 4}, {...}]
Any idea? I would appreciate some hint? I could't not find an easy solution via html though.
Thanks
you can use a for loop to access each element and display them.
Refer to this link. For loop in multidimensional javascript array
Firstly, I have replaced the square brackets using a regular expression and formed a new array. After that, I have merged object having same ID using spread operator.
You can refer to the code below which solves this problem.
let array = [
{ name: "[1][apples]", value: "2" },
{ name: "[1][melons]", value: "1" },
{ name: "[2][apples]", value: "2" },
{ name: "[2][melons]", value: "4" },
{ name: "[3][apples]", value: "3" },
{ name: "[3][melons]", value: "2" }];
let newArray = [];
let result = [];
array.forEach((obj, i) => {
let nameArray = obj.name.replace(/[\[\]']+/g, ' ').trim().split(' ');
let o = {};
o['id'] = parseInt(nameArray[0]);
o[nameArray[1]] = obj.value;
newArray.push(o);
});
for(let i = 0; i< newArray.length; i++) {
for(let j = i+1; j < newArray.length; j++) {
if(newArray[i].id === newArray[j].id) {
let o = {...newArray[i], ...newArray[j]};
result.push(o);`enter code here`
}
}
}
console.log('Final result', result);
Thanks for the input. I think my question needed to be more specific:
(1) Yes, they are always in order.
(2) My names of my input-tags in html appear to be an multidimensional array. This is not the case! I tried something, but it turned out to be for php.
I found the follow workaround:
function apiAdapter() {
var arrayToCopy = $("#formsteps").serializeArray();
var copiedArray = [];
for (let i = 0; i < arrayToCopy.length; i += 2) {
var id = arrayToCopy[i].name.slice(arrayToCopy[i].name.indexOf('[') + 1, arrayToCopy[i].name.indexOf(']'));
copiedArray.push({ "id": id, "apples": arrayToCopy[i].value, "melons": arrayToCopy[i + 1].value })
}
return copiedArray;
}
As I am new to JavaScript I always look for better solutions. So thanks again for your posts.
I have an app where I need to create a new array by pushing values from two other arrays after comparing what values in one array exist in another.
Example:
From these two arrays...
sel[1,4];
bus[1,2,3,4,5,6];
The desired result is a new object array which will populate a repeater of checkboxes in my view...
newList[{1:true},{2:false},{3:false},{4:true},{5:false},{6:false}];
The problem I'm running into, is that my code is creating duplicates and I'm not seeing why.
Here is my code:
var newList = [];
var bus = self.businesses;
var sel = self.campaign.data.businesses;
for( var b = 0; b < bus.length; b++ ){
if(sel.length > -1){
for( var s = 0; s < sel.length; s++){
if( bus[b]._id === sel[s].business_id){
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':true});
} else {
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
}
}
} else {
console.log('hit else statement');
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
}
}
I need fresh eyes on this as it looks correct to me... but obviously I'm missing something. :-)
Your code produces duplicates because you push selected: false objects into your newList every time the inner loop is run and the ids don't match:
for( var s = 0; s < sel.length; s++){
if( bus[b]._id === sel[s].business_id){
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':true});
} else {
// THIS LINE CAUSES THE DUPLICATES:
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
}
}
To fix your code, move this line out of the inner loop into the outer loop below and add a continue outer; to the inner loop's if body. Then you need to place the outer label directly in front of the outer loop: outer: for( var b = 0; b < bus.length; b++ ) ....
However, I recommend a simpler implementation as follows:
let selection = [{_id: 1, business_name: 'A'}];
let businesses = [{_id: 1, business_name: 'A'}, {_id: 2, business_name: 'B'}];
let result = businesses.map(business => ({
'business_id': business._id,
'name': business.business_name,
'selected': selection.some(selected => business._id == selected._id)
}));
console.log(result);
Appendix: Same implementation with traditional functions:
var selection = [{_id: 1, business_name: 'A'}];
var businesses = [{_id: 1, business_name: 'A'}, {_id: 2, business_name: 'B'}];
var result = businesses.map(function(business) {
return {
'business_id': business._id,
'name': business.business_name,
'selected': selection.some(function(selected) { return business._id == selected._id })
};
});
console.log(result);
I suggest to use a different approach by using an object for sel and the just iterate bus for the new array with the values.
function getArray(items, selected) {
var hash = Object.create(null);
selected.forEach(function (a) {
hash[a] = true;
});
return items.map(function (a) {
var temp = {};
temp[a] = hash[a] || false;
return temp;
});
}
console.log(getArray([1, 2, 3, 4, 5, 6], [1, 4]));
ES6 with Set
function getArray(items, selected) {
return items.map((s => a => ({ [a]: s.has(a) }))(new Set(selected)));
}
console.log(getArray([1, 2, 3, 4, 5, 6], [1, 4]));
You can use map() method on bus array and check if current value exists in sel array using includes().
var sel = [1,4];
var bus = [1,2,3,4,5,6];
var result = bus.map(e => ({[e] : sel.includes(e)}))
console.log(result)
This combines both Nina Scholz elegant ES6 approach with le_m's more specific solution to give you something that is shorter, versatile, and repurposable.
function getArray(items, selected, [...id] = selected.map(selector => selector._id)) {
return [items.map((s => a => ({
[a._id + a.business_name]: s.has(a._id)
}))(new Set(id)))];
}
console.log(...getArray([{
_id: 1,
business_name: 'A'
}, {
_id: 2,
business_name: 'B'
}, {
_id: 3,
business_name: 'C'
}, {
_id: 4,
business_name: 'D'
}, {
_id: 5,
business_name: 'E'
}, {
_id: 6,
business_name: 'F'
}], [{
_id: 1,
business_name: 'A'
}, {
_id: 2,
business_name: 'B'
}]));
I have two arrays
A =[1990,1991,....]
B=[a,b,c,d,e,f,...]
I want the resultant array in this format
Resultant=[{
name: 1990,
data: [a,b,c]
},{
name: 1991,
data: [d,e,f]
},...
]
Please help me how will I make it using for loops?
How about this:
var b= ["a","b","c","d","e","f"];
var result = [1990,1991].map(function(n){ return { name:n, data: b.splice(0,3)} });
This will format data with Array.prototype.map, based on your (rather vague) requirement:
var A = [1990,1991];
var B = ["a","b","c","d","e","f"];
var formatted = A.map(function (name, i) {
return {
name: name,
data: B.slice(i*3, i*3+3)
}
});
/*[
{
"name": 1990,
"data": [
"a",
"b",
"c"
]
},
{
"name": 1991,
"data": [
"d",
"e",
"f"
]
}
]*/
Assuming that for each in A, you want data to store 3 elements of B. I've stuck with your requirement of using for loops.
var Resultant = [];
for (var i = 0; i < a.length; i++) {
var data = [];
for (var j = 0; j < 3, B.length > 0; j++) {
data.push(B.shift());
}
Resultant.push({name: A[i], 'data': data});
}
This worked for me:
http://jsfiddle.net/s5zdD/ <-- see jsfiddle to show
A =[1990,1991,1992];
B=['a','b','c','d','e','f','g','h','i'];
var Resultant = jQuery.map(A, function(i,v){
// if no jQuery use:
// var Resultant = A.map(function(i,v){
return {
'name':A[v],
'data': B.splice(0,3)
}
})
console.log(Resultant);
Have data that has this kind of structure:
$input = [ { animal: 'cat', name: 'Rocky', value: 1 },
{ animal: 'cat', name: 'Spot', value: 2 },
{ animal: 'dog', name: 'Spot', value: 3 } ];
Need fastest possible method for converting to this format:
$output = { animal: [ 'cat', 'dog' ],
name: [ 'Rocky', 'Spot' ],
value: [ 1, 2, 3 ] };
The output should have keys equal to each of the keys in each object from the input. And the output values should be arrays with the sorted unique values. I found a few ways to do it using nested loops, but slower than I would like. With 30,000 elements to the input array with 8 keys for each of the objects, the best I have been able to do is 300ms in Chrome. Would like to get down to 100ms. Is there any faster method using a map or reduce?
Yet another way for modern browsers:
$input.reduce(function(acc, obj) {
Object.keys(obj).forEach(function(k) {
acc[k] = (acc[k] || []).concat(obj[k])
})
return acc
},{})
Here's one way.
$input = [ { animal: 'cat', name: 'Rocky', value: 1 },
{ animal: 'cat', name: 'Spot', value: 2 },
{ animal: 'dog', name: 'Spot', value: 3 } ];
$output = {animal:{},name:{},value:{}};
$input.forEach(function(v,i) {
$output.animal[v.animal] = 1;
$output.name[v.name] = 1;
$output.value[v.value] = 1;
});
$output.animal = Object.keys($output.animal);
$output.name = Object.keys($output.name);
$output.value = Object.keys($output.value);
It prevents having to test each Array every time. You can performance compare to see if it helps.
live example: http://jsfiddle.net/TJVtj/1/
If you don't want to hardcode the keys, you can make the solution generic.
var keys = Object.keys($input[0]),
$output = {};
keys.forEach(function(v) {
$output[v] = {};
});
$input.forEach(function(v) {
keys.forEach(function(vv) {
$output[vv][v[vv]] = 1;
});
});
keys.forEach(function(v) {
$output[v] = Object.keys($output[v]);
});
live example: http://jsfiddle.net/TJVtj/2/
Warning. All the values will be strings since they're fetched as object keys.
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
Above function is used to check duplicates
$output={};
for(i=0; i< $input.length; i++)
{
if(!$output.animal) $output.animal=[];
if(!$output.name) $output.name=[];
if(!$output.value) $output.value=[];
var ani=$input[i];
if(ani.animal && !inArray(ani.animal, $output.animal)) $output.animal.push(ani.animal);
if(ani.name && !inArray(ani.name, $output.name)) $output.name.push(ani.name);
if(ani.value) $output.value.push(ani.value);
}
DEMO.
// If you don't know the objects all have the same keys you need to look at each one-
var output= {},
input= [{
animal:'cat', name:'Rocky', value:1
},{
animal:'cat', name:'Spot', value:2
},{
animal:'dog', name:'Spot', value:3
}];
input.forEach(function(itm){
for(var p in itm){
if(itm.hasOwnProperty(p)){
if(!output[p]) output[p]= [];
if(output[p].indexOf(itm[p])== -1) output[p].push(itm[p]);
}
}
});
Run.expose(output)// nonstandard object to string method
// returned value: (String)
{
animal:[
'cat',
'dog'
],
name:[
'Rocky',
'Spot'
],
value:[
1,
2,
3
]
}
Try Underscore, it's magnificent with this kind of tasks)