Javascript Array of objects get single value [duplicate] - javascript

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Construct an array of elements from an array of objects? [duplicate]
(2 answers)
Closed 8 years ago.
Lets say I have an array of objects:
var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
Is there an array function that will allow me to get one property as an array,
for example:
namesArray = employees.reduceToProperty('name'); // none existent function i made up!
// should return ["George","Edward","Christine","Sarah"]
I know how get the desired result with a loop, I am just hoping for an array function or combination of functions exist that can do this in one line.

var names = employees.map(function(i) {
return i.name;
});
names is now an array containing the name-properties of the objects.

Array.prototype.map maps one array to another:
var names = employees.map(function (val) {
return val.name;
});
// ['George', 'Edward', 'Christine', 'Sarah']

If you find yourself doing this frequently, you might consider using pluck from Underscore/Lo-Dash:
var listOfPropertyNames = _.pluck(list, 'propertyName');
underscorejs.org/#pluck
lodash.com/docs#pluck
If you don't want to do include a library, it is of course possible to write your own pluck for use on your code base:
function pluck(list, propertyName) {
return list.map(function(i) {
return i[propertyName];
});
}
And running it:
pluck([{name: 'a'}, {name: 'b'}], 'name');
["a", "b"]
You'll have to decide how to handle the edge cases like:
object in the list not having the property
an undefined being in the list
?

Related

How to remove dublicate values from array of objects using javaScript? [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}]
I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance
let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']},
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
let uniqueArray = arr.values.filter(function(item, pos) {
return arr.values.indexOf(item.values) == pos;
})
console.log(uniqueArray)
}
}
You can easily remove duplicates from an Array by creating a new Set based off it.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection
If you want the result in an array, just use spread syntax for that, for example:
let arr = [{
name: 'test1',
values: ['35,5', '35,2', '35,2', '35,3', '35,5']
},
{
name: 'test2',
values: ['35,1', '35,1', '33,2', '34,3', '32,5']
}
];
const uniqueArr = arr.reduce((accum, el) => {
// Copy all the original object properties to a new object
const obj = {
...el
};
// Remove the duplicates from values by creating a Set structure
// and then spread that back into an empty array
obj.values = [...new Set(obj.values)];
accum.push(obj);
return accum;
}, []);
uniqueArr.forEach(el => console.dir(el));

JavaScript scope: preserve object in array in function [duplicate]

This question already has answers here:
How to copy JavaScript object to new variable NOT by reference? [duplicate]
(2 answers)
Closed 3 years ago.
I am using .map() on an array inside a function. I am not modifying the array itself (arr = arr.map(...)), but rather creating a new array (var arr2 = arr.map(...)).
Yet, this still modifies the original arr outside my function (which I don't want). How can I preserve?
var arr = [{prop: 1}];
myFunction(arr);
console.log(arr[0].prop); // returns 2, I want it to return 1
function myFunction(arr) {
var arr2 = arr.map(obj => {
obj.prop = 2;
return obj;
});
console.log(arr[0].prop); // returns 2
}
It modifies based on its reference. If you want to create a new object and modify its properties then you need to use Spread Syntax. Read the documentation:
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected, or an object
expression to be expanded in places where zero or more key-value pairs
(for object literals) are expected.
You can try the following:
var arr = [{prop: 1}];
myFunction(arr);
function myFunction(arr) {
var arr2 = arr.map(obj => {
let copyObj = {...obj};
copyObj.prop = 2;
return copyObj;
});
console.log(arr[0].prop);
console.log(arr2[0].prop);
}

Chaining methods on array display as undefined [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 5 years ago.
const array = new Array(9).fill([]).forEach(function(value, index, arr) {
arr[index] = Array(9).fill(0);
console.log(index, arr[index]); // This line report properly by creating
}); // new array.
console.log(array); // Reported as underdefined.
However, if redefine as below, it works as expected.
const array = new Array(9).fill([]);
array.forEach( function(value,index,arr){
arr[index] = Array(9).fill(0);
console.log(index,arr[index]);
});
console.log(array);
I would like to define multiple dimensional arrays within one line used as this state command.
But what is the problem for scenario 1 where bounded forEach methods array definitions work fine?
But what is the problem for scenario 1 where bounded forEach methods
array defnitions works fine.
Problem is forEach returns undefined
I woule like to define multiple dimensional arrays within one line
used as this.state command.
You can use map for the same
var output = new Array(9).fill([]).map( function(value,index,arr){
return Array(9).fill(0); //return the inner array
});
Or as #bergi suggested, you can use Array.from as well
var output = Array.from(Array(9)).map( function(value,index,arr){
return Array(9).fill(0);
});
As other answers have already mentioned Array.forEach returns undefined or does not return anything, you cannot use it.
As an alternate approach, you can use Array.from.
Following is a sample:
var output = Array.from({
length: 9
}, () => {
return Array.from({
length: 9
}, () => 0)
});
console.log(output)
Also, one more issue with your code is, you are using an object in Array.fill. What array.fill does is, it will create the value to be filled first and then fill it in all items.
var output = new Array(9).fill([]);
output[0].push(1);
console.log(output)
In you check the output, it says /**ref:2**/, but if you check in console, you will notice that all items will have item 1. So you should avoid using objects with Array.fill.
You want to generate array of 9 arrays filled with 0 and return it to variable.
You can achieve this using map method.
const array =
new Array(9)
.fill([])
.map(function(){
return Array(9).fill(0);
});
console.log(array);
p.s. no value, index and etc needed to pass to map methods argument in Your case
Array.prototype.forEach returns undefined. Just call the forEach like below.
const array = new Array(9).fill([])
array.forEach( function(value,index,arr){
arr[index] = Array(9).fill(0);
});
// [
// [0, 0, 0, ...],
// ...
// ]
Using map would be another choice, but I don't vote for it because it creates yet another array in memory.

Sort Javascript Object by Value [best practices?] [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 5 years ago.
Since there's no official way to sort an object by values, I'm guessing you either (1) Use an array instead or (2) Convert your object to an array using Object.entries(), sort it, then convert back to an object. But option (2) is technically unsafe since Javascript objects aren't supposed to have order.
Now I have a React app where I'm using Redux. I'm storing my data not as an array but as an object iterated by id values. This is what Redux suggests, and I would do it anyways, because of lookup times. I want to sort this redux data, so what I'm currently doing is option (2) of converting to array and then back to object. Which I don't really like.
My question is: Is this what everyone else does? Is it safe to sort an object?
Example:
const sortObject = (obj) => {
//return sorted object
}
var foo = {a: 234, b: 12, c: 130}
sortObject(foo) // {b: 12, c:130, a:234}
this is what I'm currently doing.
My object data structure looks something like this
obj = {
asjsd8jsadf: {
timestamp: 1234432832
},
nsduf8h3u29sjd: {
timestamp: 239084294
}
}
And this is how I'm sorting it
const sortObj = obj => {
const objArray = Object.entries(obj);
objArray.sort((a, b) => {
return a[1].timestamp < b[1].timestamp ? 1 : -1;
});
const objSorted = {};
objArray.forEach(key => {
objSorted[key[0]] = key[1];
});
return objSorted;
};
If you are using the Redux documentation for reference you should also have an array with all of the id's in it. Wouldn't it be easier to just sort that array and then use insertion sort when you add something to the state. Then you could use the sorted array to access the byId property of the state?

Sort array of array on string value in Javascript [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 6 years ago.
I want to sort the array of array on length of string, as follows
var arr = [
[1951, "Mayfer"],
[1785, "Actinac Capsules"],
[1007, "Ferri Injection"],
[1101, "Cetaphil"]
];
var sortedArr = sortOnLengthOfString(arr);
>> sortedArr = [
[1951, "Mayfer"],
[1101, "Cetaphil"],
[1007, "Ferri Injection"],
[1785, "Actinac Capsules"]
]
Is there a solution with lodash preferably? Or plain Javascript?
I haven't found duplicate question yet. Can someone find it? Please note, the sorting I am asking for, is for array of arrays and not array of objects.
You can use Array#sort at this context,
var obj = [
[1951, "Mayfer"],
[1785, "Actinac Capsules"],
[1007, "Ferri Injection"],
[1101, "Cetaphil"]
];
obj.sort(function(a,b){
return a[1].length - b[1].length
});
console.log(obj);
//[[1951, "Mayfer"],[1101, "Cetaphil"],[1007, "Ferri Injection"],[1785, "Actinac Capsules"]]

Categories

Resources