How to sort a bi-dimensional javascript array? [duplicate] - javascript

This question already has answers here:
Sort an array based on another array of integers
(7 answers)
Closed 8 years ago.
var global=[];
var value=[50,1,4,29];
var title=["d","b","c","a"];
title.forEach(function(title,i) {
global[title]=value[i];
})
I would like to sort the global array by value but I can't figure out how.
I precise I can't use any library jquery,underscore...
thanks !
the goal is to know what object has the less value.
a,b,c,d have values 50,1,4,29
I can sort values but how to know what's the name associated to this value ?

You're not using global[] correctly as an array in your loop. You can't reference array items with [title], you can either push to the array global.push(value[i]) or use global[i] = value[i]. If you use either of these methods you can just call 'global.sort()' to sort the array which will give you [1, 29, 4, 50]. If you want to use the array as multidimensional, you need to change your loop to something like this:
title.forEach(function(title,i) {
global[i] = {};
global[i][title]=value[i];
})
which will give you [Object { d=50}, Object { b=1}, Object { c=4}, Object { a=29}]
If you want to sort this you could use sort which takes a function in which you can write your custom sorter but I don't think you can use this as all your keys are different. If all your keys were the same, say 'value' ,i.e [Object { value=50}, Object { value=1}, Object { value=4}, Object { value=29}] , you could do:
global.sort(function(a,b) {
return parseInt(a.value, 10) - parseInt(b.value, 10);
});
but this can't be applied to your array since all the keys are different.

Related

Why when I update a nested array in the parent array and other children receive the same value? [duplicate]

This question already has answers here:
Strange behavior of an array filled by Array.prototype.fill()
(9 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 1 year ago.
I faced a strange situation when I tried to create an array of arrays via fill and then I tried to add some value to the first child I saw all other nested arrays receive this value as well.
I have an idea why it could happen. It looks like the fill property uses the same object of all 3 nested 'places\items' and now each item is the reference to the single Array.
Also, I tried to use the .fill(new Array()) instead of the literal expression but I had the same result.
I'm not sure if I'm right so fix me, please, if I missed something. Thanks
// an amount of the required output arrays
const requiredArrays = 3;
const cols = new Array(requiredArrays).fill([]);
cols[0].push({id: 1})
The expected result:
[
[
{
"id": 1
}
],
[],
[]
]
the actual result:
[
[
{
"id": 1
}
],
[
{
"id": 1
}
],
[
{
"id": 1
}
]
]
P.S. What is the right way to achieve the result I want to have? Should I just use the for cycle and populate the parent array via the children or maybe some nicer way exists?
From the fill docs at MDN:
If the first parameter is an object, each slot in the array will reference that object.
This means that you get an array of references to the same array (which is an object as well).
As to how to do it in a nicer way... that depends on what you want to achieve. Why do you need the array of arrays? Will they all have a fixed length?
Arrays are passed down by reference this makes it not that great for the fill method. Though you can fill it with a placeholder value and then map those to an array.
const requiredArrays = 3;
const cols = new Array(requiredArrays).fill('').map(() => []);
cols[0].push({id: 1})
console.log(cols);
EDIT: As pointed out in the comments, a better solution:
const requiredArrays = 3;
const cols = Array.from({length: requiredArrays}, () => []);
cols[0].push({id: 1})
console.log(cols);

Get Children of JSON Elements using Javascript? [duplicate]

This question already has answers here:
How to select nth item inside the object
(2 answers)
Closed 2 years ago.
If I were to have a Json file that looked something like this:
{
"numbers":{
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
}
and I wanted to get the value of the third number (three) using JavaScript. Instead of doing...
jsonObject.numbers.thirdnum
Is there a way I can select that value using some sort of children or index method? for example something kind of like this...
jsonObject.numbers.children[2]
First you have to convert your JSON to JavaScript:
const object = JSON.parse(string_of_json);
Then you can get an array of an objects properties, keys, or both with the appropriate methods on the Object class.
Object.keys(object.numbers)[2];
Object.values(object.numbers)[2];
Object.entries(object.numbers)[2];
Since order isn't guaranteed, this isn't generally useful unless you want to do something to every item item you get back.
If you want to access them by position then you should usually write your orignal JSON to use an array instead of an object.
{
"numbers": [ "one", "two", "three", "four", "five" ]
}
You can use Object.values to convert the values to an array and attach the index.
obj = {
"numbers":{
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
}
console.log(Object.values(obj.numbers)[3])
After you parse JSON it became Object, so
const obj = {
"numbers": {
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
};
console.log(obj.numbers[Object.keys(obj.numbers)[2]]);

How can I get an object inside an array in JavaScript? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I have a for loop and I would like to tap into an object inside the array I am looping. Specifically I would like to tap into the "Name" section of my objects to only console.log the names, not the whole array. This is the code... I am doing this with Mongoose but I don't think it has anything to do with my problem, I just wanted to add it tho.
const newCustomerNum2 = new customerList({
name: "John",
age: 32
});
customerList.find(function(err, customers) {
if (err) {
console.log(err);
} else {
for (var i = 0; i<customers.length; i++){
console.log(customers.name);
}
}
});
What is happening in your for loop, is that you are looping over the indices of your array.
Let's say you array has 3 elements, the for loop would be called with i = 0, then i = 1, then i = 2.
This index can be used to reference an object in your array.
When you are calling customers.name you are trying to access the property name on the array rather than the data in it.
If you want to access the objects inside your array, use the subscript expression:
customers[i] where 0 < i < customers.length.
That way, you can use console.log(customers[i].name) in your loop.
In addition, you could simply use the for ... of expression, which iterates over the elements of an array:
for (let customer of customers) {
console.log(customer.name);
}

Getting an object from n object array if I have one of the keys [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
I have a very complex object that looks like this:
[
{type: "type", data: {a ton more stuff}},
//with tons of these objects.
]
What I am wondering is if all 'type' keys are unique, could I get the object within the array with the given type or will I need to loop through the json array every time?? What I really need is the data, but I only know the type. This is a database schema that is not mine so unfortunately I cannot change the object.
There may be a more efficient way, but you could use Array.prototype.find():
const item = items.find(i => i.type === 'yourType');
You could also loop through once and create a Map if type is unique, using type as the key and the object as the value. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
Short answer is yes. Since it is an array of objects you need to loop through it. What you need is
const newArr = oldArr.filter(obj => (obj.type && obj.type === 'myType' && obj.data) ? obj.data : false));

How to sort a List using a object's properties as the list object and value as the order?

I asked the same kind of question here
How to sort an ArrayList using a Map key as list object and value as the order?
But I need an equivalent for JavaScript. I need to keep the order of my list of objects as it can be changed and reordered anytime in my webapp.
In my model I have a array list of objects example
objectList = [object1, object2, object3, object4]
and I save the order of each object belonging to this instance to a another object example:
order
{
"object1":4,
"object2":2,
"object3":1,
"object4":3
}
Therefore i want to sort my list according to its value in the order object's property retrieved by the objects Id as the key:
Expected result:
[object3, object2, object4, object1]
In Java this works
objectList.sort(Comparator.comparing(o -> yourMap.get(o.getId()));
However I am unsure how to achieve this same sort in JavaScript
EDIT
Just to clarify, I do not want to sort the order object. I want to sort my objectList using its order maintained in the order object
The order of object keys are never guaranteed. You can create an array of the object values, using Object.values and then sort them
const data = {
"object1": 4,
"object2": 2,
"object3": 1,
"object4": 3
};
const sortedVal = Object.values(data).sort((a, b) => a - b);
console.log(sortedVal)
This does the trick and retrieves order value by using the objects id for the key. Then we just compare these values for sorting
this.objectList.sort(function(a, b)
{
if(order[a._id] > order[b._id]) return 1;
if(order[b._id] > order[a._id]) return -1;
return 0;
});

Categories

Resources