update value of each item in associative array - javascript

I have a JavaScript associative array, say:
var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";
How can I update value of each item in this array, so that output should be,
myArray["id1"] = "newValue";
myArray["id2"] = "newValue";
myArray["id3"] = "newValue";

Get all property name array using Object.keys() and then iterate over them update property value using Array#forEach method.
var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";
Object.keys(myArray).forEach(function(k) {
myArray[k] = 'newVal';
});
console.log(myArray);
Faster way using a while loop.
var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";
var names = Object.keys(myArray),
i = names.length;
while (i--) {
myArray[names[i]] = 'newVal';
};
console.log(myArray);

Use for in loop
Its always advisable to use hasOwnProperty to iterate across only the non-inherited properties.
var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";
for (var prop in myArray) {
if (myArray.hasOwnProperty(prop)) {
myArray[prop] = 'newValue';
}
}
console.log(myArray);

Related

How do I delete an array inside an array?

I want to delete an array entry.
I have already used the splice method, but it doesn't work.
var clients = new Array();
//-----
var tmp = new Array();
tmp["connection"] = connection;
tmp["authentificated"] = 1;
tmp["username"] = rows[0].username;
tmp["rank"] = rows[0].rank;
clients.push(tmp);
This doesn't work:
clients.splice(index, 1);
Do you have any ideas, where the mistake is?
Thanks in advance.
you can use like below.
var clients = new Array();
var tmp = new Array();
tmp["connection"] = "hi";
tmp["authentificated"] = 1;
clients.push(tmp);
var tmp1 = new Array();
tmp1["connection"] = "hi";
tmp1["authentificated"] = 2;
clients.push(tmp1);
var index = 0;
delete clients[index];
console.log(clients);
but the issue with delete is that the length of the array will remain same because delete only removes the object from the element in the array

How to build an array from a string in javascript?

I am trying to grab some values out of a sting that looks like this:
W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748
I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...]
I have this snippet that does the trick, but only for the first value:
var foo = str.substring(str.indexOf(":") + 1);
Use split().
Demo here: http://jsfiddle.net/y9JNU/
var keys = [];
var values = [];
str.split(', ').forEach(function(pair) {
pair = pair.split(':');
keys.push(pair[0]);
values.push(pair[1]);
});
Without forEach() (IE < 9):
var keys = [];
var values = [];
var pairs = str.split(', ');
for (var i = 0, n = pairs.length; i < n; i++) {
var pair = pairs[i].split(':');
keys.push(pair[0]);
values.push(pair[1]);
};
This will give you the keys and values arrays
var keys = str.match(/\w+(?=:)/g),
values = str.match(/[\d.]+(?=,|$)/g);
RegExp visuals
/\w+(?=:)/g
/[\d.]+(?=,|$)/g
And another solution without using regexp
var pairs = str.split(" "),
keys = pairs.map(function(e) { return e.split(":")[0]; }),
values = pairs.map(function(e) { return e.split(":")[1]; });
JSFiddle
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";
var all = str.split(","),
arrayOne = [],
arrayTwo = [];
for (var i = 0; i < all.length; i++) {
arrayOne.push(all[i].split(':')[0]);
arrayTwo.push(all[i].split(':')[1]);
}
parse the string to an array
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";
var tokens = str.split(",");
var values = tokens.map(function (d) {
var i = d.indexOf(":");
return +d.substr(i + 1);
});
var keys = tokens.map(function (d) {
var i = d.indexOf(":");
return d.substr(0, i);
});
console.log(values);
console.log(keys);
http://jsfiddle.net/mjTWX/1/ here is the demo

Find missing element by comparing 2 2D-Arrays in Javascript

A few days ago I posted a thread asking on how to find the missing element when passing a method 2 JS arrays. As you can see here. I've been trying to figure out now how to modify the method so that instead of passing it 2 Arrays you pass it 2 2D-Arrays... Having some trouble though:
/*var sml = new Array();
sml[0] = new Array("dean","22");
sml[1] = new Array("james","31");
sml[2] = new Array("ludwig","35");
var lrg = new Array();
lrg[0] = new Array("dean","22");
lrg[1] = new Array("james","31");
lrg[2] = new Array("ludwig","35");
lrg[3] = new Array("kevin","23");
lrg[4] = new Array("elton","40");*/
var sml = new Array();
sml[0] = "dean";
sml[1] = "james";
sml[2] = "ludwig";
var lrg = new Array();
lrg[0] = "dean";
lrg[1] = "james";
lrg[2] = "ludwig";
lrg[3] = "kevin";
lrg[4] = "elton";
var deselected = findDeselectedItem(sml, lrg);
alert("Deselected Items: " + deselected[0]+", "+ deselected[1]);
// -------------------------------------------------------------- //
function findDeselectedItem(CurrentArray, PreviousArray) {
var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
var deselectedItems = new Array();
// loop through previous array
for (var j = 0; j < PreviousArrSize; j++) {
// look for same thing in new array
if (CurrentArray.indexOf(PreviousArray[j]) == -1)
deselectedItems.push(PreviousArray[j]);
}
if (deselectedItems.length != 0) {
return deselectedItems;
} else {
return null;
}
}​
Now if you run the above code it works perfectly, but if you go and uncomment the variable declarations on top that that pushes arrays ontop of the array, and then comment out the simple strings that get pushed on top of the array, it doesn't work as well... For instance:
var sml = new Array();
sml[0] = new Array("dean","22");
sml[1] = new Array("james","31");
sml[2] = new Array("ludwig","35");
var lrg = new Array();
lrg[0] = new Array("dean","22");
lrg[1] = new Array("james","31");
lrg[2] = new Array("ludwig","35");
lrg[3] = new Array("kevin","23");
lrg[4] = new Array("elton","40");
/*var sml = new Array();
sml[0] = "dean";
sml[1] = "james";
sml[2] = "ludwig";
var lrg = new Array();
lrg[0] = "dean";
lrg[1] = "james";
lrg[2] = "ludwig";
lrg[3] = "kevin";
lrg[4] = "elton";*/
var deselected = findDeselectedItem(sml, lrg);
alert("Deselected Items: " + deselected[0]+", "+ deselected[1]);
// -------------------------------------------------------------- //
function findDeselectedItem(CurrentArray, PreviousArray) {
var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
var deselectedItems = new Array();
// loop through previous array
for (var j = 0; j < PreviousArrSize; j++) {
// look for same thing in new array
if (CurrentArray.indexOf(PreviousArray[j][0]) == -1)
deselectedItems.push(PreviousArray[j][0]);
}
if (deselectedItems.length != 0) {
return deselectedItems;
} else {
return null;
}
}​
The method returns 2 completely wrong values. PS - I'm not interested in the "numbers" just yet, just the "names" for now...
Your CurrentArray is 2-dimensional and indexOf compares Arrays but not first elements of that Arrays. So you need to use:
for ( var i = 0; i < CurrentArray.length; ++i){
if (CurrentArray[i][0] == PreviousArray[j][0]){
deselectedItems.push(PreviousArray[j][0]);
break;
}
}
Instead of
if (CurrentArray.indexOf(PreviousArray[j][0]) == -1)
deselectedItems.push(PreviousArray[j][0]);
You could also rearrange the array like this:
var sml = {};
sml["dean"] = 22;
sml["james"] = 31;
sml["ludwig"] = 35;
var lrg = {};
lrg["dean"] = 22;
lrg["james"] = 31;
lrg["ludwig"] = 35;
lrg["kevin"] = 23;
lrg["elton"] = 40;
and use:
function findDeselectedItem(c,p){
ret=[];
for (var i in p){
if (p.hasOwnProperty(i)){
if ('undefined'===typeof c[i]) {
ret.push(i);
}
}
}
return ret;
}
alert(findDeselectedItem(sml, lrg));
Demo: http://jsfiddle.net/LsrCj/
indexOf function will check object equality in this case; to make it return something else than -1 you've to pass same 2D array instances to sml and lrg.
new Array("dean","22") === new Array("dean","22") //false
Keep the same instances (e.g. http://jsfiddle.net/3TQYz/) in both arrays or use your own indexOf test that would recursively check values of the array to make your case working.

Can't add to javascript array in loop

I'm having some issues with the following code:
var tmpArray = new Array();
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
alert(fnlArray[n] +"-"+ largest.val);
tmpArray[n] = fnlArray[n];
}
}
fnlArray contents is:
fnlArray['result1'] = 1;
fnlArray['result2'] = 2;
fnlArray['result3'] = 2;
fnlArray['result4'] = 2;
and largest.val = 2;
The issue I'm having is the alert gets fired so I would expect to end up with tmpArray with the following:
tmpArray['result2'] = 2;
tmpArray['result3'] = 2;
tmpArray['result4'] = 2;
But the array (tmpArray) is always empty. Is this an issue with adding items to the array dynamically within a loop?
var tmpArray = new Array(); should be:
var tmpArray = {};
Your tmpArray object is not a index array, so you have to use object literals.
var tmpArray = {};
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
tmpArray[n] = fnlArray[n];
}
}
alert(JSON.stringify(tmpArray)); //Prints: {"result2":2,"result3":2,"result4":2}
Demo: http://jsfiddle.net/QhFGF/

Array value count javascript

How can I count the array depending on the value..
I have an array with this value..
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
I need to count the array depending on the value
Array with Value A is 2
Array with value B is 1
Thanks!
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function count(array, value) {
var counter = 0;
for(var i=0;i<array.length;i++) {
if (array[i] === value) counter++;
}
return counter;
}
var result = count(myArr, "a");
alert(result);
If you're interested in a built-in function... you could always add your own.
Array.prototype.count = function(value) {
var counter = 0;
for(var i=0;i<this.length;i++) {
if (this[i] === value) counter++;
}
return counter;
};
Then you could use it like this.
var result = myArr.count("a");
alert(result);
Oh well, beaten to the punch, but here's my version.
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b"
getCountFromVal( 'a', myArr );
function getCountFromVal( val, arr )
{
var total = arr.length;
var matches = 0;
for( var i = 0; i < total; i++ )
{
if( arr[i] === val )
{
matches++;
}
}
console.log(matches);
return matches;
}
Live Demo: http://jsfiddle.net/CLjyj/1/
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function getNum(aVal)
{
num=0;
for(i=0;i<myArr.length;i++)
{
if(myArr[i]==aVal)
num++;
}
return num;
}
alert(getNum('a')); //here is the use
I would use Array.filter
var arr = ['a', 'b', 'b']
arr.filter(val => val === 'b').length // 2
Everyone's already given the obvious function, so I'm going to try and make another solution:
var myArr = [];
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
function count(arr, value){
var tempArr = arr.join('').split(''), //Creates a copy instead of a reference
matches = 0,
foundIndex = tempArr.indexOf(value); //Find the index of the value's first occurence
while(foundIndex !== -1){
tempArr.splice(foundIndex, 1); //Remove that value so you can find the next
foundIndex = tempArr.indexOf(value);
matches++;
}
return matches;
}
//Call it this way
document.write(count(myArr, 'b'));
Demo
You can use Lodash's countBy function:
_.countBy(myArr);
Example:
var myArr = new Array(3);
myArr[0] = "a";
myArr[1] = "a";
myArr[2] = "b";
const result = _.countBy(myArr);
// Get the count of `a` value
console.log('a', result.a);
// Get the count of `b` value
console.log('b', result.b);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
countBy Documentation

Categories