How to create arrays based on array of objects value? - javascript

I'm working on a task where I've to make arrays based on certain values in array of objects.
Input Array:
const array = [{
name: 'A',
age: points: { x: 100, y: 107}
},
{
name: 'B',
age: points: { x: 210, y: 107}
},
{
name: 'C',
age: points: { x: 110, y: 107}
},
{
name: 'D',
age: points: { x: 230, y: 107}
}
];
Expected Output:
[
[
{
name: 'A',
age: points: { x: 100, y: 107}
},
{
name: 'C',
age: points: { x: 110, y: 107}
}
],
[
{
name: 'B',
age: points: { x: 210, y: 107}
},
{
name: 'D',
age: points: { x: 230, y: 107}
}
]
]
Note: here condition value will be dynamic, for example, the points following under certain conditions can be fall in one array, if that out of condition then-new array will be formed and so on, there may be 200+ objects in the array.
In case new object occur as
{
name: 'D',
age: points: { x: 230, y: 107}
}
then a new array of object ll be formed and all objects falling in that condition should get added to that.
Please put your valuable suggestions.
Thanks in advance.

Your question isn't completely clear. From what I can guess, you have an array of objects, you need to store an empty result array. Then, consume the "dynamic conditions" one by one, use a filter method on the original array and keep adding the results on to the result array.
Here's some pseudocode:
let dataArray = [<your objects>];
let resultArray = [];
while(<dynamic condtions list is not empty>)
{
resultArray.push(dataArray.filter(item=>{
// write your filter logic based on your current dynamic condition here
if(item satisifes condition)
return true;
else
return false;
}))
}
console.log(resultArray);

Related

nodejs/JS: Objects not being updated in array [duplicate]

This question already has answers here:
Push object in Javascript
(3 answers)
Closed 2 years ago.
Firstly, I am a complete noob to Javascript and Node.js.
I tried to write a simple program that creates an array of planes that all have the same values except in index, which should take on the value of each index in the for loop from 0 - 2.
Here is my code
var plane = {
index: -1,
name: "A380",
seats: {
first: 40,
buisness: 90,
economy: 300
},
wheels: 8,
}
var planeArray = []
for (var i = 0; i < 3; i++) {
plane.index = i
planeArray.push(plane)
}
console.log(planeArray)
But when I print the output, the indices of all the planes are 2. Here is my output.
[
{
index: 2,
name: 'A380',
seats: { first: 40, buisness: 90, economy: 300 },
wheels: 8
},
{
index: 2,
name: 'A380',
seats: { first: 40, buisness: 90, economy: 300 },
wheels: 8
},
{
index: 2,
name: 'A380',
seats: { first: 40, buisness: 90, economy: 300 },
wheels: 8
}
]
Here is my expected output.
[
{
index: 0,
name: 'A380',
seats: { first: 40, buisness: 90, economy: 300 },
wheels: 8
},
{
index: 1,
name: 'A380',
seats: { first: 40, buisness: 90, economy: 300 },
wheels: 8
},
{
index: 2,
name: 'A380',
seats: { first: 40, buisness: 90, economy: 300 },
wheels: 8
}
]
I don't understand why.
Could someone help me out. Also, any additional explanations/resources helpful for learning node.js would be greatly appreciated
The problem here is that the object being added in the array goes as a reference and not as the value of the object
you can either try either of the below two solutions.
This way you pass the object value instead of its reference.
for (var i = 0; i < 3; i++) {
plane.index = i
planeArray.push({...plane})
}
for (var i = 0; i < 3; i++) {
plane.index = i
planeArray.push(JSON.parse(JSON.stringify(plane)))
}
You are always changing the same object with plane.index = i. If you want to have three different entries in your array you need three different objects.

Pushing x and y values into array variables

I have an array with variables. I would like to push some x and y coordinates into the array, but when i try to push instead of changing the variable values the push creates new variables and assign the value to those.
So it looks like this
0: {id: "t523470", name: "tPm1", x: 0, y: 0, parent: null, …}
1: {id: "t523471", name: "tPm2", x: 0, y: 0, parent: null, …}
2: {y: 651, x: 446}
3: {y: 800.015625, x: 802.328125}
Instead of this
0: {id: "t523470", name: "tPm1", x: 446, y: 651, parent: null, …}
1: {id: "t523471", name: "tPm2", x: 802.328125, y: 800.015625, parent: null, …}
function getModulePosition(id) {
for (let i = 0; i < axisViewElements.modules.length; i++) {
let currentElement = axisViewElements.modules[i].id;
if (id === currentElement) {
continue;
}
let module = document.getElementById(currentElement);
let modulePos = { x: module.getBoundingClientRect().left, y: module.getBoundingClientRect().top }
console.log(modulePos);
axisViewElements.modules.push({
y: modulePos.y,
x: modulePos.x
});
}
}
Array push method always insert a new element into an array. As you need to update an existing element you can simply do this:
axisViewElements.modules[i].y = modulePos.y;
axisViewElements.modules[i].x = modulePos.x;
Array.prototype.push always creates a new index with your values. You cannot use .push() and expect to change previous values in the Array. For your purpose you have to loop through your array, find the indexes you want to change some values in them and then assign your new values to them.
You are pushing to array which always creates a new element.
I'm assuming that your elements are unique inside array with respect to their id attribute. So you have to find the element with the id and then update the x and y attributes.
Your code will be like this:
elementToUpdate = axisViewElements.modules.find(el => el.id === you_id)
elementToUpdate.x = modulePos.x
elementToUpdate.y = modulePos.y
Try it here https://runkit.com/embed/pd68veqr5ey7
let input = [
{id: "t523470", name: "tPm1", x: 0, y: 0, parent: null},
{id: "t523471", name: "tPm2", x: 0, y: 0, parent: null}
];
let newValue = [
{y: 651, x: 446},
{y: 800.015625, x: 802.328125}
];
input.forEach((item, index) => item = Object.assign( item , newValue[index]));
console.log(input);

How to update values not present in one array of objects from another array of objects?

I have two arrays of objects which contain a huge amount of data.
The structure of these two arrays goes something like this.
arr1 = [
{x: 1, y: '2018-01-01'},
{x: 2, y: '2018-01-02'},
{x: 3, y: '2018-01-03'},
{x: 5, y: '2018-01-05'},
....
]
arr2 = [
{x: 1, y: '2018-01-01'},
{x: 2, y: '2018-01-02'},
{x: 3, y: '2018-01-03'},
{x: 4, y: '2018-01-04'},
{x: 5, y: '2018-01-05'},
{x: 6, y: '2018-01-08'}
]
I want to update arr2 in such a way that it updates the array of objects with values that are only present in arr1 and drop any values not present in arr1. Note, I want to update the original arr2 and not return a new array.
I tried iterating through individual arrays and remove values not present but not luck.
You could get a map and iterate from the end for splicing unknown items or update changed values.
var arr1 = [{ x: 1, y: '2018-01-01x' }, { x: 2, y: '2018-01-02' }, { x: 3, y: '2018-01-03' }, { x: 5, y: '2018-01-05' }],
arr2 = [{ x: 1, y: '2018-01-01' }, { x: 2, y: '2018-01-02' }, { x: 3, y: '2018-01-03' }, { x: 4, y: '2018-01-04' }, { x: 5, y: '2018-01-05' }, { x: 6, y: '2018-01-08' }],
map = arr1.reduce((m, { x, y }) => m.set(x, y), new Map),
i = arr2.length;
while (i--) {
if (map.has(arr2[i].x)) {
if (map.get(arr2[i].x) !== arr2[i].y) {
arr2[i].y = map.get(arr2[i].x);
}
} else {
arr2.splice(i, 1);
}
}
console.log(arr2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter array by comparing two arrays of objects with different elements in their objects?

How to filter array by comparing two arrays of objects with different elements in their objects?
I have:
arr1 =[{ x: 1, y: 2, z:3 }, { x: 2, y: 1, z:4 }];
arr2 = [{ x: 1, y: 2, a:5 }, { x: 2, y: 3, a:4 }];
I want to compare x and y values from both arrays and return the not macthing object from first array, in the above example return [{ x: 2, y: 1, z:4 }]
I tried to use _.differenceWith(arr1, arr2, _.isEqual); but obviously for this the arrays should have similar objects which is not my case.
You are very close to the right answer.
The _.differenceWith function from lodash has three arguments, the array to inspect, the values to exclude and the third argument is a comparator which determines which values you need. In your case, using _.isEqual is looking for exactly the same object (which as far as I understood is not your desired behavior).
If you only care about having same x and y values, try using your custom comparator instead of the _.isEqual function from lodash.
It would look something like this:
const arr1 = [{ x: 1, y: 2, z:3 }, { x: 2, y: 1, z:4 }];
const arr2 = [{ x: 1, y: 2, a:5 }, { x: 2, y: 3, a:4 }];
// this is your custom comparator which is called with each value from the two arrays
// I gave descriptive names to the arguments so that it is more clear
const customComparator = (valueFromFirstArray, valueFromSecondArray) =>
valueFromFirstArray.x === valueFromSecondArray.x
&& valueFromFirstArray.y === valueFromSecondArray.y;
const result = _.differenceWith(arr1, arr2, customComparator);
console.log(result);
// will print [{x: 2, y: 1, z: 4}]
Or if you are not familiar with arrow functions, the custom comparator can be declared like this:
function customComparator(valueFromFirstArray, valueFromSecondArray) {
return valueFromFirstArray.x === valueFromSecondArray.x
&& valueFromFirstArray.y === valueFromSecondArray.y
}
Here is a fiddle where you can mingle around with the custom comparator if you'd like to.
Use the filter function
arr1 =[{ x: 1, y: 2, z:3 }, { x: 2, y: 1, z:4 }];
arr2 = [{ x: 1, y: 2, a:5 }, { x: 2, y: 3, a:4 }];
let notMatched = arr2.filter(function (item, index) {
return !(item.x === arr1[index].x && item.y == arr1[index].y);
});
console.log(notMatched);

JavaScript filter array function

I've made a list of ships that it represented like so:
var fleet =
["RMS MARY", 2000, 15],
["TITANIC 2", 10000, 13],
["Boaty McBoatface", 2000, 18],
["Jutlandia", 1945, 10],
["Hjejlen", 250, 8]
];
I want to write a function that will filter the ships by a given capacity.
Example:
filterByCapacity(fleet,5000)
This should only return the ship Titanic 2 since it is the only ship with a capacity higher than 5000.
Any ideas on how to write such a function?
Easy :
function filterByCapacity(fleet, capacity) {
var filteredArray = [];
for (var i = 0; i < fleet.length; i++) {
// Supposing we know that the capacity is the second index in the array
if (fleet[i][1] >= capacity) // Or you can make this strictly greather than (>)
filteredArray.push(fleet[i]);
}
return (filteredArray);
}
But I suggest you use objects rather than arrays. Something more like this :
var fleet = [
{
name: "RMS MARY",
capacity: 2000,
age: 15, // I had no idea what the third index meant so I made up one
},
{
name: "TITANIC 2",
capacity: 10000,
age: 13,
},
{
name: "Boaty McBoatface",
capacity: 2000,
age: 18,
},
{
name: "Jutlandia",
capacity: 1945,
age: 10,
},
{
name: "Hjejlen",
capacity: 250,
age: 8,
}
];
That way you can make one generic function filterBy(fleet, paramName, paramValue) that could return you the ships that match the filter
First, I'd like to point out that your array was badly made. You were missing a left square bracket on the first entry ("RMS MARY".) The corrected array is below:
var fleet = [
["RMS MARY", 2000, 15],
["TITANIC 2", 10000, 13],
["Boaty McBoatface", 2000, 18],
["Jutlandia", 1945, 10],
["Hjejlen", 250, 8],
];
Second, I'd recommend that you represent the ships with objects instead of arrays, so you'd have something like this:
var fleet = {
{name: "RMS MARY", capacity: 2000, somethingElse: 15},
{name: "TITANIC 2", capacity: 10000, somethingElse: 13},
{name: "Boaty McBoatface", capacity: 2000, somethingElse: 18},
{name: "Jutlandia", capacity: 1945, somethingElse: 10},
{name: "Hjejlen", capacity: 250, somethingElse: 8},
};
Now, as for the function you want, I'll provide two, one for the original array representation of ships, and one for the object representation:
//array representation
function filterByCapacity(fleet, capacity){
return fleet.filter(function(ship){
return ship[1] >= capacity;
});
}
//object representation
function filterByCapacity(fleet, capacity){
return fleet.filter(function(ship){
return ship.capacity >= capacity;
});
}
Hope this helps.
Represent your ships as objects:
var fleet = [
{name: "RMS Mary", capacity: 2000, whatever: 15},
...
];
Then you can use filter in a way that is readable and makes sense.
function filterByCapacity(fleetArr, minCapacity) {
return fleetArr.filter(function(ship) {
return ship.capacity > minCapacity;
});
}
console.log(filterByCapacity(fleet, 5000)) // only Titanic

Categories

Resources