I have a javascript array of objects: each object contains key/value pairs. I'm trying to iterate through this array, and delete any object whose value for a particular key (say "Industry") fails to match a given value. Here is my code, for some reason it's not looping through the whole array, and I think it has something to do with the fact that when I delete an item the loop counter is botched somehow:
var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {
var asset = assets_results[i];
var asset_industry = asset['industry'];
if (industry != asset_industry) { assets_results.splice(i,1); }
}
Any ideas? Thanks in advance.
This is because when you splice one element, the size of array decreases by one. All elements after the splice shift one position to the beginning of the array and fills the space of spliced one. So the code misses one element.Try this code.
var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {
var asset = assets_results[i];
var asset_industry = asset['industry'];
if (industry != asset_industry) {
assets_results.splice(i,1);
i--;
}
}
This is a common problem when modifying an object while iterating through it. The best way to avoid this problem is, rather than deleting pairs from the existing array if they fail the test, to create a new array and only add pairs if they pass the test.
var industry = 'testing';
var i = 0;
var asset_results_filtered = [];
for (i = 0; i < assets_results.length; i++) {
if (industry == assets_results[i]) {
asset_results_filtered.push(assets_results[i]);
}
}
EDIT: Your code looked a bit illogical — I modified the example to use the variables given.
splice removes an element from an array and resizes it :
var arra = ['A', 'B', 'C', 'D'];
arr.splice(1,2); // -> ['A', 'D'];
Which means that you should not increment i when you splice, because you skip the next element. splicing will make of the i + 2 element the i + 1 element.
var industry = 'testing';
for (var i = 0, max = assets_results.length; i < max; ) { // Accessing a property is expensive.
if (industry != assets_results[i]['industry']) {
assets_results.splice(i,1);
} else {
++i;
}
}
Try this instead:
var industry = 'testing';
var i = assets_results.length - 1;
for (; i > 0; i--) {
var asset = assets_results[i],
asset_industry = asset['industry'];
if (industry != asset_industry) { assets_results.splice(i,1); }
}
Related
Let's say that I'm doing this because of my homework. I would like to develop some kind of schedule for the week to come (array of 6-7 elements - output result). But I have one problem. I need to figure it out how one element be positioned in the array and also his frequency must be exactly what user input is. Elements must be positioned at different index in the array.
I'm having that kind of input from user (just an example);
var arrayOfElements = ["el1","el2","el3"];
var el1Frequency = 3;
var el2Frequency = 2;
var el3Frequency = 1;
//output array of schedule (this is just an example)
var finaloutPutArray = ["el1","el2","el3","el1","el2","el1"];
Index of elements el1 is 0, 3 and 5, basically, I don't want elements to be repeated like this;
["el1","el1","el2","el3"...];
["el2","el1","el1","el3"];
Can you please give me some ideas on how to solve this problem.
I started like this;
var finalSchedule = [];
var totalDaysPerWeek = 6;
for(var i =0; i < totalDaysPerWeek; i++) {
...
}
This is one pattern, check my working snippet:
var arrayOfElements = ["el1","el2","el3"];
var obj = { el1: 3,
el2: 2,
el3: 1};
// First determine the max recurring of an element, this will be the number of cycles fo your loop
// Check key values
var arr = Object.keys(obj).map(function ( key ) { return obj[key]; });
// Get max value
var max = Math.max.apply( null, arr );
var finalArray = [];
// Iterate from 0 to max val
for(i = 0; i < max; i += 1){
// Iterate on array of elements
for(k = 0; k < arrayOfElements.length; k += 1) {
// If config of recurring
if( obj[arrayOfElements[k]] >= i+1 ) {
// Push into array
finalArray.push(arrayOfElements[k]);
}
}
}
console.log(finalArray);
Given an array and a length, I want to derive every possible combination of elements (non-repeating) at the specific length.
So given an array of:
arr = ['a','b','c','d']
and a length of 3, I'm after a function that outputs a 2-dimensional array as follows:
result = [
['a','b','c'],
['b','c','a'],
['c','a','b'],
. . . etc.
]
I've tried tackling this and have had a deal of difficulty.
The following code uses a brute-force approach. It generates every permutation of every combination of the desired length. Permutations are checked against a dictionary to avoid repeating them in the result.
function makePermutations(data, length) {
var current = new Array(length), used = new Array(length),
seen = {}, result = [];
function permute(pos) {
if (pos == length) { // Do we have a complete combination?
if (!seen[current]) { // Check whether we've seen it before.
seen[current] = true; // If not, save it.
result.push(current.slice());
}
return;
}
for (var i = 0; i < data.length; ++i) {
if (!used[i]) { // Have we used this element before?
used[i] = true; // If not, insert it and recurse.
current[pos] = data[i];
permute(pos+1);
used[i] = false; // Reset after the recursive call.
}
}
}
permute(0);
return result;
}
var permutations = makePermutations(['a', 'a', 'b', 'b'], 3);
for (var i = 0; i < permutations.length; ++i) {
document.write('['+permutations[i].join(', ')+']<br />');
}
How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?
JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?
The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}
I try to merge two node list in one but when I concat in one array, there is two time the same node. Concat do not search if nodes to insert already exist in array...
var firstNodelist = document.querySelectorAll("#outter, #inner");
var finalArray = new Array();
for (var i = 0; i < firstNodelist.length; i++) {
var secondNodelist = firstNodelist[i].querySelectorAll("div");
var firstArray = new Array();
for (var x = 0; x < secondNodelist.length; x++) {
firstArray.push(secondNodelist[x]);
}
finalArray = finalArray.concat(firstArray)
}
console.log("FINAL", finalArray);
The jsfiddle exemple
Rather than building a second, unnecessary array within your loop, just use that inner loop to check whether the node is already in the array (Array#indexOf on all modern browsers) and only add it if it isn't.
var firstNodelist = document.querySelectorAll("#outter, #inner");
var finalArray = []; // `[]` rather than `new Array()`
for (var i = 0; i < firstNodelist.length; i++) {
var secondNodelist = firstNodelist[i].querySelectorAll("div");
for (var x = 0; x < secondNodelist.length; x++) {
// Get this node
var node = secondNodeList[x];
// Is it in the array already?
if (finalArray.indexOf(node) === -1) {
// No, put it there
finalArray.push(node);
}
}
}
console.log("FINAL", finalArray);
Be sure to test your target environment(s) to be sure they have Array#indexOf.
Having said that, there's a much better way for that specific situation: Live Example | Live Source
var finalArray = Array.prototype.slice.call(
document.querySelectorAll("#outter div, #inner div")
);
...since querySelectorAll won't include the same node more than once, even if #inner is inside #outter (or vice-versa). (The Array.prototype.slice.call(someObject) is a trick to get a true array from any array-like object.)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/