I have this:
var Test = new Array();
Test = ("Rose","India",564,375,new Array(5,6,7),".net");
But I want to define the keys for this array:
Test = ("Rose" => "Pleb",
"India" => "Test",
564,
375,
new Array(5,6,7),
".net");
But that doesn't work. How is this done?
You wouldn't do this with array. What's called an associative array wikipedia in some languages is simply an object in JS. To declare an object with given properties, use an object literal:
var Test = {
Rose: "Pleb",
India: "Test",
'a-b': 'c,d',
0: 564,
1: 375,
2: [5,6,7],
3: ".net"
};
There are two data structures in javascript, arrays and objects (actually, arrays are a special kind of object, but don't be concerned about that for now). An array is a collection with integer keys; the keys may be non-contiguous (i.e. they don't need to go 0,1,2,3, they might go 0,51,52,99,102). You can assign named properties to an array, but that makes iterating over them more difficult.
An object is a collection of arbitrarily-named keys that can be accessed very similarly to an array.
The simplest way to instantiate an array is as an array literal (which uses the square bracket notation), while the simplest way to create an object is with object literal (which uses curly-bracket notation):
var myArray = []; // creates a new empty array
var myOtherArray = [ "foo", "bar", "baz"]; // creates an array literal:
// myOtherArray[0] === "foo"
// myOtherArray[1] === "bar"
// myOtherArray[2] === "baz"
//
//
// This would be reasonably called a multidimensional array:
//
var myNestedArray = [ [ "foo", "bar", "baz"], [ "one", "two", "three"] ];
// myNestedArray[0] => [ "foo", "bar", "baz"];
// myNestedArray[1] => [ "one", "two", "three"];
// myNestedArray[0][0] === "foo";
// myNestedArray[1][0] === "one";
var myObject = {}; // creates an empty object literal
var myOtherObject = {
one: "foo",
two: "bar",
three: "baz"
};
// myOtherObject.one === "foo"
// myOtherObject["one"] === "foo" (you can access using brackets as well)
// myOtherObject.two === "bar"
// myOtherObject.three === "baz"
//
//
// You can nest the two like this:
var myNestedObject = {
anArray: [ "foo", "bar", "baz" ],
anObject: {
one: "foo",
two: "bar",
three: "baz"
}
}
You could perhaps try something of this approach:
// Declare an array to hold all of the data grid values
var dataGridArray = [];
// Turn dataGridArray into a 2D array
for (arrayCounter = 0; arrayCounter < document.getElementById("cphMain_dtgTimesheet").rows.length - 2; arrayCounter++) {
// Create a new array within the original array
dataGridArray[arrayCounter] = [];
} // for arrayCounter
I hope this was of some help =).
Related
This question already has answers here:
Counting the occurrences / frequency of array elements
(39 answers)
Closed 4 months ago.
Say I have array like this:
[
"foo",
"bar",
"foo"
"bar",
"bar",
"bar",
"zoom"
]
I want to group it so I can get a count like so:
{
"foo": 2,
"bar": 4,
"zoom": 1
}
is there a utility that can do this?
Just use the function Array.prototype.reduce.
let array = [ "foo", "bar", "foo", "bar", "bar", "bar", "zoom"],
result = array.reduce((a, c) => (a[c] = (a[c] || 0) + 1, a), Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Yes you can reduce() your array to an object with the keys and the count, like this:
const input = [
"foo",
"bar",
"foo",
"bar",
"bar",
"bar",
"zoom"
];
const result = input.reduce((total, value) => {
total[value] = (total[value] || 0) + 1;
return total;
}, {});
console.log(result);
Hope it helps!
You can do this in a concise way via reduce:
var arr = [ "foo", "bar", "foo", "bar", "bar", "bar", "zoom" ]
var result = arr.reduce((r,c) => (r[c] = (r[c] || 0) + 1, r), {})
console.log(result)
It gets really cute if you ware to use lodash and _.countBy:
var arr = [ "foo", "bar", "foo", "bar", "bar", "bar", "zoom" ]
var result = _.countBy(arr);
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
You could use the reduce() method which is avalible on the array object to achieve this grouping. So, something along the lines of this might achieve what you're after:
var input = [
"foo",
"bar",
"foo",
"bar",
"bar",
"bar",
"zoom"
]
// Iterate the input list and construct a grouping via a "reducer"
var output = input.reduce(function(grouping, item) {
// If the current list item does not yet exist in grouping, set
// it's initial count to 1
if( grouping[item] === undefined ) {
grouping[item] = 1;
}
// If current list item does exist in grouping, increment the
// count
else {
grouping[item] ++;
}
return grouping;
}, {})
console.log(output)
Yeah I guess with Array.prototype.reduce, it's just:
const map = list.reduce((a, b) => {
a[b] = a[b] || 0;
return ++a[b], a;
}, {});
wondering if there is less verbose way tho.
Explanation: First, we create object (a brand new empty object). Secondly using the spread operator we first copy everything from the existing array and make a new array out of it and use that to create a new Set (the Set object lets you store unique values) and use that as the key, and finally we filter out our array (with a little help from the length property) to see how many times a particular key occurs and set that to the object's value. And remember, since we used Object.assign() and put everything inside of it, so what gets returned is an object containing the result of everything that I tried to explain (to the best of my knowledge) above :) We also used the comma operator here which simply evaluates each of its operands (from left to right) and returns the value of the last operand.
const arr = ["foo", "bar", "foo", "bar", "bar", "bar", "zoom"];
const data = Object.assign({}, ...Array.from(new Set(arr), key => ({[key]: arr.filter(value => value === key).length})));
console.log(data);
This might be a noob question for you guys but I just want to clarify something. I'm new to JS and I know that arrays are just objects with fields as indexes.
I have some lines of code here. The objective is pretty easy, is to pass a parameter function to an array and map it to another one.
My confusion is that the _obj is declared as an object with _obj = {}, and we have to do _obj[obj.key] = obj.value to map the keys and values. What is actually going around here?
It makes me feel like there are two nested arrays and it feels gross. I hope you understand me and I just need to know if there is another way or what actually is going on.
Stay at home guys!
Thanks in advance.
const objArray = [
{key:1, value:10},
{key:2, value:20},
{key:3, value:30},
{key:4, value:40}
];
const newArray = objArray.map(obj => {
let _obj = {};
_obj[obj.key] = obj.value;
return _obj;
});
console.log(newArray);
//Array [Object { 1: 10 }, Object { 2: 20 }, Object { 3: 30 }, Object { 4: 40 }]
I just need to know if there is another way or what actually is going
on.
When you do:
_obj[obj.key] = obj.value;
... you are setting a key/property on the object _obj to hold a particular value. In this case, the key you are setting is the value of obj.key and the value is obj.value. The values of obj.key and obj.value changes depending on what object you are iterated on in the .map() callback. For example, if you are looking at the first object in your array, obj.key would be 1 and obj.value would be 10. Thus, doing _obj[obj.key] = obj.value would be equivalent to _obj[1] = 10, which sets the key of 1 to have the value of 10 on the _obj object:
{
1: 10
}
This process occurs for each object in your array.
As for a different approach, you could use computed-property names introduced in ES6 with destructuring assignment to return an object literal with the key property as the key for the new object literal and the value property and the actual value for the new object:
const objArray = [
{key:1, value:10},
{key:2, value:20},
{key:3, value:30},
{key:4, value:40}
];
const newArray = objArray.map(({key, value}) => ({[key]: value}));
console.log(newArray);
In javascript, just like java, everything that is not a primitive is an object. Arrays are actually an object that just have some utility functions added in, such as the length attribute, and .map. To access a property, you can either do obj.prop, or use an arbitrary string like python's dictionaries like obj["prop"].
Array is special object, In which all key should be Number. The array has some pre-defined method, Which is made to iterate and perform similar operations. The array is linear and implements stack implementation. Array element could be any other object or Array.
To understand:
const object = {
1: "something",
2: "something2"
}
const object2 = {
"1_1": "something",
"2_1": "something2"
}
// console.log(object[1])
// console.log(object[2])
// console.log(object2["2_1"]) // Key string
// console.log(object2["1_1"])
// object.forEach(console.log) // Error
const array = ["something", "something2"]
const array2 = []
array2["1_1"] = "something"
array2["2_1"] = "something2"
console.log(array[0]) // index start with 0, default
console.log(array[1])
console.log(array2["2_1"]) // Key string
console.log(array2["1_1"]) // Works
array.forEach(console.log) // No error, something 0 [ 'something', 'something2' ] something2 1 [ 'something', 'something2' ]
array2.forEach(console.log) // No error, // No output
Here is the variant with reduce method:
const objArray = [
{key:1, value:10},
{key:2, value:20},
{key:3, value:30},
{key:4, value:40}
];
const newArray = objArray.reduce((acc, rec) => { return {...acc, [rec.key]: rec.value} }, []);
console.log(JSON.stringify(newArray))
// {"1":10,"2":20,"3":30,"4":40}
I am trying to get values from the following object. The for loop works in one of the objects but won't in the other javascript object. I was wondering what the difference and how can I get it to work in the other object?
Object 1:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
}
];
Object 2:
{
"4dd5a49e366": {
"name" : "bar",
"bar" : "sit",
"date": "2016-08-03T04:48:04.283Z"
},
"519c5056af2": {
"name" : "lorem",
"bar" : "ipsum",
"date": "2016-09-03T04:48:04.283Z"
}
}
I want to do a search for items where name attribute is matching some search_term. And return the items.
Here is the search for loops am using.
function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var i in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('o'));
This works for the first object and not for the second. How can I get it to work for the second?
The first variable is an array of objects. Since it is an array you can use all array methods on it.
Second one is an object with keys 4dd5a49e366 & 519c5056af2 which in turn are again object and have few properties.
You cannot use array methods on this second object
how can I get it to work in the other object?
Hope this snippet will be useful
var myObject = {
"4dd5a49e366": {
"name": "bar",
"bar": "sit",
"date": "2016-08-03T04:48:04.283Z"
},
"519c5056af2": {
"name": "lorem",
"bar": "ipsum",
"date": "2016-09-03T04:48:04.283Z"
}
}
// a function to accept the name value
function findByName(name) {
var thisObject = "";
for (var keys in myObject) { // looping over objects
var getThisObject = myObject[keys];
if (getThisObject.name === name) { // Checking if name matches
thisObject = myObject[keys]; // assigning the object to a variable
}
}
return thisObject // return that variable
}
var getMyObject = findByName('bar');
console.log(getMyObject)
JSFIDDLE
EDIT
if I enter just findByName('b'); it should return results that the
full name
You need to use indexOf to find if this name value contains the specific character.
Use an array to store all the relevant object where the name value contains this specific character.Return that array from the function.
function findByName(name) {
var thisObject = [];
for (var keys in myObject) {
var getThisObject = myObject[keys];
if (getThisObject.name.indexOf(name)!==-1) {
thisObject.push(myObject[keys]);
}
}
return thisObject
}
var getMyObject = findByName('b');
JSFIDDLE 2
I suggest you do some reading on JavaScript Object literals and Arrays. The first example is an array of objects. The second is just an object. Two completely different data structures.
How do I push new values to the following array?
json = {"cool":"34.33","alsocool":"45454"}
I tried json.push("coolness":"34.33");, but it didn't work.
It's not an array.
var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
or
var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)
var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.
var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push ( {"cool":"34.39","also cool":"45459"} );
Your variable is a javascript object {} not an array [].
You could do:
var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";
and
var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };
Later, you add those objects to your array: array.push (o, o2);
Also JSON is simply a string representation of a javascript object, thus:
var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again
That is an object, not an array. So you would do:
var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
Object vs Array: JavaScript
Use the push() function to append to an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
Now array is
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
];
// append multiple values to the array
arr.push("Salut", "Hey");
Now array is
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
"Salut"
"Hey"
];
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Will print:
Hi
Hello
Bonjour
Hola
Salut
Hey
Update
If you want to add the items of one array to another array, you can use Array.concat:
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Will print
["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]
var arr = [foo,bar,xyz];
arr[arr.indexOf('bar')] = true;
Is there an easier way to do this in JS?
You could just use objects.
var obj = {foo: true, baz: false, xyz: true};
obj.baz = true;
All values in that array are already undefined. (You edited your post) I don't know why you are complaining about 2 whole lines of code though.
Short answer no, you can't access an index of an array without knowing the index.
One IE safe way would be to create a prototyped function which lets you set it easily:
Array.prototype.setKeysWithValue = function(keyValue,newValue)
{
var i;
for (i in this)
{
if (this[i] === keyValue)
this[i] = newValue;
}
}
This can then be used like:
var arr = ['foo','bar','xyz'];
arr.setKeysWithValue('bar',true);
In your example you would really only be replacing "bar" with true; your resultant array would look like [foo, true, xyz].
I think it's assumed that what you're asking for is an alternative to having one set of arrays for keys and one set of arrays for values, of which there is no better way.
However, you can use an associative array, or objects, to maintain a key value pair.
var f = false, t = true;
// associative array
var arr = new Array();
arr["foo"] = arr["bar"] = arr["foobar"] = f;
arr["bar"] = t;
// object
var obj;
obj = {"foo":f, "bar":f, "foobar":f};
obj["bar"] = t;
// the difference is seen when you set arr[0]=t and obj[0]=t
// the array still maintains it's array class, while the object
// is still a true object
It's important to realize a few things if you use this method:
the array.length no longer applies, as it only accounts arrays by numerical index, it does not count array properties, which is what the keys in an associative array are
looping through keys/properties becomes a little more difficult since the Array object should have some native properties/methods
you may only have one key/value pair. The array structure you listed would be allowed to have [foo, bar, xyz, bar, foobar, foo], where the index should return the first occurrence in anything browser other than IE<=8
One other way to do what you were specifically asking is:
Array.prototype.replace = function(from,to){ this[this.indexOf(from)]=to; };
Array.prototype.replaceAll = function(from,to){ while(this.indexOf(from)>=0){this[this.indexOf(from)]=to;} };
var arr = new Array();
arr=[ "foo", "bar", "foobar", "foo" ];
arr.replace("bar",true); // [ "foo", true, "foobar", "foo" ]
arr.replaceAll("foo",false); // [ false, true, "foobar", false ]