Related
const pairs = { a : 1, b : 2, c : 3 }
const keyArray = [a, b, c]
I'm trying to get a function or w/e that returns [1, 2, 3]. can't think of anything please help
In javascript all keys of an object are actually strings, and can be addressed using the same strings.
Your code is creating an array containing the values of the - possibly uninitialized - variables a, b and c, which then produces [undefined, undefined, undefined], or else whatever those variables contain.
You need to make keyArray contain strings instead, and then you can use the map() function to produce the desired result:
const pairs = { "a" : 1, "b" : 2, "c": 3 }
const keyArray = ["a", "b", "c"]
const values = keyArray.map(key => pairs[key]);
console.log(values);
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
const keyArray = ['a', 'b', 'c']
for(const item of keyArray)
{
console.log(pairs[item])
}
You need to make your items inside the array and object as strings
Well since it's Javascript
Object.values() should do it.
const keyArray = Object.values(pairs)
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
for(const [key , value] of Object.entries(pairs))
{
console.log(key) // a , b, c
console.log(value) // 1, 2, 3
}
This question already has answers here:
Counting elements in an array and adding them into an object [duplicate]
(2 answers)
Closed 4 years ago.
If I had an array of letters how would I go about turning each letter into an object key with a value of how many there are in that array in JavaScript?
For example:
const array = ['a', 'b', 'c', 'c', 'd', 'a'];
const obj = { a: 2, b: 1, c: 2, d: 1};
Objects can be indexed very similarly to arrays in JavaScript, like so:
const obj = {};
array.forEach((element) => {
//Check if that field exists on the object to avoid null pointer
if (!obj[element]) {
obj[element] = 1;
} else {
obj[element]++;
}
}
you can simply use Array.reduce() to create a frequency map :
const array = ['a', 'b', 'c', 'c', 'd', 'a'];
let result = array.reduce((a, curr) => {
a[curr] = (a[curr] || 0)+1;
return a;
},{});
console.log(result);
How to I change the object in the array with For-of loop?
Following code:
let arr = ['a', 'b', 'c', 'd', 'e'];
for (let v of arr) {
if (v === 'c') {
v = 'f';
break;
}
}
console.log(arr);
I want to find the first letter c and change it to an f, but arr doesn't get changed, probably because it is not referenced ? But shouldn't the v of arr make that the object v is the same as the one in arr ?
Javascript does not create references to simple values such String. To get array referrenced, you need to let array be an array of objects like [{char : 'a'}, {char : 'b'}, ...]. Then in your iterator you can change elements of array through changing of the char property
let arr = [{char: 'a'}, {char :'b'}, ...];
for (let v of arr) {
if (v.char === 'c') {
v.char = 'f';
break;
}
}
v is not a reference to the array element, it's just a variable that is assigned the value that the array iterator yields. If you assign to it, only the variable v changes but not the array.
To do that, you need to explicitly reference the property with its index and assign to it:
let arr = ['a', 'b', 'c', 'd', 'e'];
for (let [i, v] of arr.entries()) {
if (v === 'c') {
arr[i] = 'f';
break;
}
}
console.log(arr); // ['a', 'b', 'f', 'd', 'e']
An iterator does not provide a way to mutate the underlying structure, you need to do it yourself.
As detailed in the MDN spec, let is declaring a new variable from a copy of your array element. So changing the v will not change the value in the array. This is shared by var and const and is simply just javascripts behaviour. When you create a new object, it starts empty.
Your loop is basically saying "For every element in arr, declare a variable holding a copy of it and then if that variable is c, change that copy to f"
Before you change v both, the array and v point to - or in this case have - the same value:
arr[2] -> 'c' <- v
After you change v it has a different value, but you didn't change the array:
arr[2] -> 'c' v -> 'f'
v and arr[2] are only placeholders, but different ones.
The correct answer:
let arr = ['a', 'b', 'c', 'd', 'e'];
let i = 0;
for (let v of arr) {
if (v == 'c') {
arr[i] = 'f';
break;
}
i++;
}
console.log(arr);
:-P
I'll start this by saying, I understand there are many ways to do this. This question is an effort to compare different version.
I also understand we're looking for SO to be a QA site, not a QAAAAAAA... site.
So I'll refine the question to make it more focused and end up with one answer.
Given an object:
var obj = {a: 1, b: 2, c: 3};
Find out if the following keys are present:
var keys = ['a', 'b', 'c', 'd']; // 'd' would be flagged although a boolean would suffice
Ideally I'd like to do this in ES5, but ES6 is more than welcome.
Ideally without the use of lodash, but it's more than welcome.
I'm sure there's a lovely combination of the native Array methods that'll work:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
The aim is to have a function or line of code that's small and concise rather than something like:
var obj = {a: 1, b: 2, c: 3};
var keys = ['a', 'b', 'c', 'd'];
var found = keys.length;
for (var i = 0; i < keys.length; i++) {
if (obj.hasOwnProperty(keys[i])) {
found--;
}
}
console.log("Missing:", found);
I'll wade in with the first offering:
var obj = {a: 1, b: 2, c: 3};
var keys = ['a', 'b', 'c', 'd'];
var allPresent = Object.keys(obj).filter(function(item) {
return keys.indexOf(item) !== -1;
}).length === keys.length;
console.log("All present:", allPresent);
Like this:
var obj = {a: 1, b: 2, c: 3};
var keys = ['a', 'b', 'c', 'd'];
alert(keys.every(Object.prototype.hasOwnProperty, obj))
allPresent = keys.reduce(function ( acc, next ) {
return !acc || obj.hasOwnProperty(next);
}, true);
Although Amits answer is probably even smaller and preferred for browsers that support 'every'. (should be all of them by now)
Given object:
var obj = {a: 1, b: 2, c: 3},
keys = ['a','b'];
You can check if it contains key 'a' using this:
Object.keys( obj ).indexOf('a') !== -1
Thanks for comments here is full answer to check what OP requested for full equality:
JSON.stringify( Object.keys( obj ) ) === JSON.stringify( keys )
Or partial equality
JSON.stringify( Object.keys( obj ) ).indexOf( JSON.stringify( keys ) ) !== -1
In javascript, is there an easy way to sort key-value pairs by the value (assume the value is numeric), and return the key? A jQuery way to do this would be useful as well.
(There are a lot of related questions about key-value pairs here, but I can't find one specifically about sorting.)
There's nothing easy to do this cross-browser. Assuming an array such as
var a = [
{key: "foo", value: 10},
{key: "bar", value: 1},
{key: "baz", value: 5}
];
... you can get an array of the key properties sorted by value as follows:
var sorted = a.slice(0).sort(function(a, b) {
return a.value - b.value;
});
var keys = [];
for (var i = 0, len = sorted.length; i < len; ++i) {
keys[i] = sorted[i].key;
}
// keys is ["bar", "baz", "foo"];
Let's assume we have an Array of Objects, like:
var data = [
{foo: 6},
{foo: 2},
{foo: 13},
{foo: 8}
];
We can call Array.prototype.sort()help, use Array.prototype.map()help to map a new array and Object.keys()help to grab the key:
var keys = data.sort(function(a,b) {
return a.foo - b.foo;
}).map(function(elem, index, arr) {
return Object.keys(elem)[0];
});
Be aware of, Array.prototype.map() requires Javascript 1.6 and Object.keys() is ECMAscript5 (requires Javascript 1.8.5).
You'll find alternative code for all those methods on MDC.
As far as I know, there isn't a built-in Javascript function to sort an array by its keys.
However, it shouldn't take too much code to do it: just extract the keys into their own array, sort them using the normal sort function, and rebuild the array in the right order. Something like this should do the trick:
function SortArrayByKeys(inputarray) {
var arraykeys=[];
for(var k in inputarray) {arraykeys.push(k);}
arraykeys.sort();
var outputarray=[];
for(var i=0; i<arraykeys.length; i++) {
outputarray[arraykeys[i]]=inputarray[arraykeys[i]];
}
return outputarray;
}
Now you can just call your function like so:
var myarray = {'eee':12, 'blah':34 'what'=>66, 'spoon':11, 'snarglies':22};
myarray = SortArrayByKeys(myarray);
And the output will be:
{'blah':34, 'eee':12, 'spoon':11, 'snarglies':22, 'what':66}
Hope that helps.
Working test page here: http://jsfiddle.net/6Ev3S/
Given
var object = {
'a': 5,
'b': 11,
'c': 1,
'd': 2,
'e': 6
}
You can sort object's keys by their values using the following:
Object.keys(object).sort(function (a, b) {
return object[a] - object[b]
}))
Result
[ 'c', 'd', 'a', 'e', 'b' ]
If you can't count on the exended array and object properties,
you can use the original Array methods-
function keysbyValue(O){
var A= [];
for(var p in O){
if(O.hasOwnProperty(p)) A.push([p, O[p]]);
}
A.sort(function(a, b){
var a1= a[1], b1= b[1];
return a1-b1;
});
for(var i= 0, L= A.length; i<L; i++){
A[i]= A[i][0];
}
return A;
}
//test
var Obj={a: 20, b: 2, c: 100, d: 10, e: -10};
keysbyValue(Obj)
/* returned value: (Array)
e,b,d,a,c
*/