Clean way of extracting object member values from an array of objects into their own array in JS [duplicate] - javascript

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 8 years ago.
Wonder if there is a cleaner way of doing this then just iterating over every single object, and incrementally rebuilding the array (in Javascript).
var myArray = [{id:10,name:'bob'},{id:30,name:'mike'},{id:40,name:'jay'},{id:50,name:'chris'},{id:60,name:'snake'}];
Indented array output --> [10,30,40,50,60]

map is an higher-order function that applies a function to every member of an array, returning the resulting array.
var myArray = [{
id: 10,
name: 'bob'
}, {
id: 30,
name: 'mike'
}, {
id: 40,
name: 'jay'
}, {
id: 50,
name: 'chris'
}, {
id: 60,
name: 'snake'
}];
myArray.map(function (obj) {
return obj.id;
}); // [10, 30, 40, 50, 60]
Note that this method is absent from IE before version 9, but you can use a polyfill instead if you need to support those browsers.
If you already reference jQuery, $.map offers the same functionality. I suppose underscore.js and the likes also offer an alternative.

Related

How to get second duplicate value rather than first value from JSON Array in React JS using lodash? [duplicate]

This question already has an answer here:
Lodash uniqBy update the latest value
(1 answer)
Closed 9 months ago.
I am working on one project where I need to remove duplicate values from JSON array object with some specification in react JS. I have tried to remove using _.uniqBy but in the output it took very first value from duplicate value which is I don't want.
Suppose You have an array JSON like:
[ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ]
using _.uniqBy I got [ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }] this output.
but I want [ { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ] this output.
As you can see I want output whose name is alice not bob along with id:1.
Can anyone help me?
Thank you.
My first thought is to use a reduce, and shove the items in a map, then get the values:
Object.values(items.reduce((map, item) => ({ ...map, [item.id]: item }), {}))
This is probably not very efficient though if you're dealing with large arrays of have performance concerns.
It's a quick and dirty one-liner. If you want something more efficient I'd take a look at the lodash source code and tweak it to your needs or write something similar:
https://github.com/lodash/lodash/blob/2f79053d7bc7c9c9561a30dda202b3dcd2b72b90/.internal/baseUniq.js

Why does pushing this object into my array give me a number? [duplicate]

This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
javascript push returning number instead of object [duplicate]
(1 answer)
Pushing objects in an array only returns last object pushed
(5 answers)
How to use Array.push and return the pushed item?
(3 answers)
Closed 2 years ago.
So, I was building a simple rest api on node, I fixed the problem, but I was just curious as to why I even get a number 4 to begin with? You'll know what I mean when you look at the code, It's just a small snippet of code that I'm confused about.
main.js
const people = [
{ id: 1, firstName: "Daniel"},
{ id: 2, firstName: "Erika" },
{ id: 3, firstName: "Christian"},
];
let person = people.push({ id: people.length + 1, firstName: "Mark"})
If I console.log(person) I get 4 as a value. I mean I understand that If I console.log(people) I will get what I added, but I'm just curious as to why when I console.log(person) I get a value of 4?
Ciao, as #VLAZ said, Array.push returns the new length of your people array.
If you want to get the last person inserted in people array you could do:
const people = [
{ id: 1, firstName: "Daniel"},
{ id: 2, firstName: "Erika" },
{ id: 3, firstName: "Christian"},
];
let person = people[people.push({ id: people.length + 1, firstName: "Mark"}) - 1];
console.log(person)
-1 because the 4th element of the array is the object in position 3

JS array : filter() with map() vs forEach() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
Which is more optimized way .filter() + .map() OR .forEach() ?
Here is a sample array of objects:
var personnel = [
{
id: 5,
name: "Luke Skywalker",
pilotingScore: 98,
shootingScore: 56,
isForceUser: true,
},
{
id: 82,
name: "Sabine Wren",
pilotingScore: 73,
shootingScore: 99,
isForceUser: false,
},
{
id: 22,
name: "Zeb Orellios",
pilotingScore: 20,
shootingScore: 59,
isForceUser: false,
},
{
id: 15,
name: "Ezra Bridger",
pilotingScore: 43,
shootingScore: 67,
isForceUser: true,
},
{
id: 11,
name: "Caleb Dume",
pilotingScore: 71,
shootingScore: 85,
isForceUser: true,
},
];
And let say we want to get the final array giving only name and id where isForceUser=true
[ { id: 5, name: 'Luke Skywalker' }, 
{ id: 15, name: 'Ezra Bridger' }, 
{ id: 11, name: 'Caleb Dume' } ] 
Now there are 2 ways ti solve it :
By using .filter()+.map(), as shown below:
var APersonnel = personnel
.filter((person) => person.isForceUser)
.map((person) => ({ id: person.id, name: person.name }));
By using .forEach() and pushing a new object:
var BPersonnel = [];
personnel.forEach((person) => {
if (person.isForceUser) {
BPersonnel.push({ id: person.id, name: person.name });
}
});
Which one of the solutions defined above is better and why?
These are not the things you should seek performance improvements in. You are talking about 'personnel' here. Which is a fairly limited array set, I imagine. If you are having performance issues, I suggest you use the chrome dev performance tab to see what's causing it.
To answer your question, filter + map is semantically easier for the eye, which again is a personal opinion. Strictly performance wise the forEach is faster, where most likely a basic of for loop is even faster. But again, these are a few milliseconds we are talking about. Which does not justify the cost of rewriting :)
Another way can be to use reduce, less code, and only one loop:
const APersonnel = personell.reduce((acc, person) => {
if (person.isForceUser) {
acc.push({ id: person.id, name: person.name });
}
return acc;
}, []);
The best way is using foreach. Because map and filter are going to create two arrays. foreach doesn't create arrays. So foreach is the best one. look at those statements bellow,
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
I could be wrong, but I'm guessing forEach would be better.
In the first scenario, you are looping across 5 items, and then again across 3 items.
In the second scenario you are just looping across 5 items. And the if in the foreach is effectively being done in the filter anyway.
There may be an exception if you're working with an extremely large set of data because you would have both arrays in memory, but for anything short of that, I would recommend forEach

How to check if array of object contains a string [duplicate]

This question already has answers here:
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 3 years ago.
let's say I have an array of objects:
let arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
I need to check whether that array includes the name 'Jack' for example using:
if (arr.includes('Jack')) {
// don't add name to arr
} else {
// push name into the arr
}
but arr.includes('Jack') returns false, how can I check if an array of objects includes the name?
Since you need to check the object property value in the array, you can try with Array​.prototype​.some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
let arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
var r = arr.some(i => i.name.includes('Jack'));
console.log(r);

What's the JavaScript way of updating an array of objects from another array? [duplicate]

This question already has answers here:
JavaScript merging objects by id [duplicate]
(18 answers)
Closed 6 years ago.
I have an object called probe. It has a property called sensors which is an array.
var probe = {
sensors = [
{ id: 1, checked: false },
{ id: 2, checked: true },
{ id: 3, checked: false },
... //more sensors
],
... //other properties
}
I have separate array which has an updated list of sensors like below.
var updatedSensors = [
{ id: 1, checked: true },
{ id: 3, checked: true }
];
I want to update the sensors array in the probe object from the values in the updatedSensors. How would I do that?
This can be easily achieved by using a couple of for-loops. But for-loops are not the pretty way of iterating in JavaScript, so I was wondering how to do this the preferred way.
Edit:
The objects in the updatedSensors is a subset of objects in probe.sensors. In other words, updatedSensors does not have all the objects (ids) that are there in the probe.sensors, but probe.sensors has all the objects (ids) that are in the updatedSensors.
Thanks.
Try this bit of code:
probe.sensors.map(function (sensor) {
// Loop through updated sensors & match sensor.id so we can reassign val
updatedSensors.map(function (f) {
if (f.id == sensor.id) {
sensor.checked = f.checked
}
})
return sensor;
})

Categories

Resources