Javascript Grouping and Sorting - javascript

I have random cities list as below . How can I group and sort it with below criteria
SortAndGroup function should take input of the countryCode and sort accordingly with capitol city on each group at first position followed by cities in that country. Thank you for your help.
randonCities =
[
{
"name": "Delhi",
"countryCode": "IN",
"isCapitol": true
},
{
"name": "New York",
"countryCode": "USA",
"isCapitol": false
},
{
"name": "Birmingham",
"countryCode": "UK",
"isCapitol": false
},
{
"name": "London",
"countryCode": "UK",
"isCapitol": true
},
{
"name": "Hyderabad",
"countryCode": "IN",
"isCapitol": false
},
{
"name": "Chicago",
"countryCode": "USA",
"isCapitol": false
},
{
"name": "Bristol",
"countryCode": "UK",
"isCapitol": false
},
{
"name": "Washington",
"countryCode": "USA",
"isCapitol": true
}
]
End Result should be
sortByCountry(USA, UK, IND) =
[
{
"name": "Washington",
"countryCode": "USA",
"isCapitol": true
},
{
"name": "Chicago",
"countryCode": "USA",
"isCapitol": false
},
{
"name": "New York",
"countryCode": "USA",
"isCapitol": false
},
{
"name": "London",
"countryCode": "UK",
"isCapitol": true
},
{
"name": "Birmingham",
"countryCode": "UK",
"isCapitol": false
},
{
"name": "Bristol",
"countryCode": "UK",
"isCapitol": false
},
{
"name": "Delhi",
"countryCode": "IN",
"isCapitol": true
},
{
"name": "Hyderabad",
"countryCode": "IN",
"isCapitol": false
}
]

You could get the order from an array (with corresponding country names) and sort by capitol.
const
sortByCountry = (...countries) => (a, b) =>
countries.indexOf(a.countryCode) - countries.indexOf(b.countryCode) ||
b.isCapitol - a.isCapitol,
array = [{ name: "Delhi", countryCode: "IN", isCapitol: true }, { name: "New York", countryCode: "USA", isCapitol: false }, { name: "Birmingham", countryCode: "UK", isCapitol: false }, { name: "London", countryCode: "UK", isCapitol: true }, { name: "Hyderabad", countryCode: "IN", isCapitol: false }, { name: "Chicago", countryCode: "USA", isCapitol: false }, { name: "Bristol", countryCode: "UK", isCapitol: false }, { name: "Washington", countryCode: "USA", isCapitol: true }];
array.sort(sortByCountry('USA', 'UK', 'IN'));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES5
var sortByCountry = function () {
var countries = Array.prototype.slice.call(arguments);
return function (a, b) {
return countries.indexOf(a.countryCode) - countries.indexOf(b.countryCode) ||
b.isCapitol - a.isCapitol;
}
},
array = [{ name: "Delhi", countryCode: "IN", isCapitol: true }, { name: "New York", countryCode: "USA", isCapitol: false }, { name: "Birmingham", countryCode: "UK", isCapitol: false }, { name: "London", countryCode: "UK", isCapitol: true }, { name: "Hyderabad", countryCode: "IN", isCapitol: false }, { name: "Chicago", countryCode: "USA", isCapitol: false }, { name: "Bristol", countryCode: "UK", isCapitol: false }, { name: "Washington", countryCode: "USA", isCapitol: true }];
array.sort(sortByCountry('USA', 'UK', 'IN'));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

In order to sort an array, you can use:
arr.sort([compareFunction])
So you would have to write a custom compareFunction
The compareFunction compares two any elements of the array and should return 1 if the first element is "bigger" or -1 if the first element is "smaller"
arr.sort((a, b) => (a > b) ? 1 : -1)
In this case our sorting function can receive any number of parameters, so we can access them in the arguments object. We can convert the arguments object into an array and use the indexOf function to compare the position of the country code in the array.
When the country code is the same, we check if one of the items is capitol.
randomCities =
[
{
"name": "Delhi",
"countryCode": "IN",
"isCapitol": true
},
{
"name": "New York",
"countryCode": "USA",
"isCapitol": false
},
{
"name": "Birmingham",
"countryCode": "UK",
"isCapitol": false
},
{
"name": "London",
"countryCode": "UK",
"isCapitol": true
},
{
"name": "Hyderabad",
"countryCode": "IN",
"isCapitol": false
},
{
"name": "Chicago",
"countryCode": "USA",
"isCapitol": false
},
{
"name": "Bristol",
"countryCode": "UK",
"isCapitol": false
},
{
"name": "Washington",
"countryCode": "USA",
"isCapitol": true
}
]
function sortByCountry(){
var args = Array.from(arguments);
randomCities.sort( (a, b) => (args.indexOf(a.countryCode) == args.indexOf(b.countryCode)) ? (a.isCapitol ? -1 : 1) : ((args.indexOf(a.countryCode) > args.indexOf(b.countryCode)) ? 1 : -1));
return randomCities;
}
sortyByCountry('USA', 'UK', 'IN');

You could do it using Array.prototype.sort() method and sort the country code by creating an ordering array, then by capital and at last, by city name.
const sortByCountry = (data, order) =>
data.sort(
(x, y) =>
order.indexOf(x.countryCode) - order.indexOf(y.countryCode) ||
y.isCapitol - x.isCapitol ||
x.name.localeCompare(y.name)
);
const data = [
{
name: 'Delhi',
countryCode: 'IN',
isCapitol: true,
},
{
name: 'New York',
countryCode: 'USA',
isCapitol: false,
},
{
name: 'Birmingham',
countryCode: 'UK',
isCapitol: false,
},
{
name: 'London',
countryCode: 'UK',
isCapitol: true,
},
{
name: 'Hyderabad',
countryCode: 'IN',
isCapitol: false,
},
{
name: 'Chicago',
countryCode: 'USA',
isCapitol: false,
},
{
name: 'Bristol',
countryCode: 'UK',
isCapitol: false,
},
{
name: 'Washington',
countryCode: 'USA',
isCapitol: true,
},
];
const order = ['IND', 'USA', 'UK'];
console.log(sortByCountry(data, order));

Related

reconstruct an array of objects from another object array

Currently, I have an array in Javascript named locations, described below:
let locations = [
{
"id": "1",
"city": "Kermit",
"state": "TX",
},
{
"id": "2",
"city": "Bloomington",
"state": "MN",
},
{
"id": "3",
"city": "Pauls Valley",
"state": "OK",
},
{
"id": "4",
"city": "Colville",
"state": "WA",
},
{
"id": "5",
"city": "Jacksboro",
"state": "TX",
},
{
"id": "6",
"city": "Shallowater",
"state": "TX"
}
]
using Javascript, I need to create another array from this array by filtering out the cities with the same states as a single array within the locations array.
required output:
locations = [
TX:[{
"id": "1",
"city": "Kermit",
"state": "TX",
},
{
"id": "5",
"city": "Jacksboro",
"state": "TX",
},
{
"id": "6",
"city": "Shallowater",
"state": "TX"
}
],
MN:[
{
"id": "2",
"city": "Bloomington",
"state": "MN",
},
],
OK:[
{
"id": "3",
"city": "Pauls Valley",
"state": "OK",
},
],
WA:[
{
"id": "4",
"city": "Colville",
"state": "WA",
},
]
]
Also, I need this array sorted in alphabetical order. If some one could give me a good approach to solve this scenario, it would be a great help.
const locations = [
{ "id": "1", "city": "Kermit", "state": "TX" },
{ "id": "2", "city": "Bloomington", "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville", "state": "WA" },
{ "id": "5", "city": "Jacksboro", "state": "TX" },
{ "id": "6", "city": "Shallowater", "state": "TX" }
];
const byState = {};
[...locations].sort((a,b) =>
a.state.localeCompare(b.state) || a.city.localeCompare(b.city)
).forEach(i => (byState[i.state]??=[]).push(i));
console.log(byState);
You can reduce the locations into groups by state. Once you have achieved that, you can convert the object key-value pairs to entries, sort them, and then convert them back into an object.
const locations = [
{ "id": "1", "city": "Kermit", "state": "TX" },
{ "id": "2", "city": "Bloomington", "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville", "state": "WA" },
{ "id": "5", "city": "Jacksboro", "state": "TX" },
{ "id": "6", "city": "Shallowater", "state": "TX" }
];
const sortObjectKeys = (obj) =>
Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
const groupedByState = sortObjectKeys(
locations.reduce((acc, location) => ({
...acc,
[location.state]: [...(acc[location.state] ?? []), {
...location
}]
}), {}));
console.log(groupedByState);
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to forgo sorting, just reduce the data:
const locations = [
{ "id": "1", "city": "Kermit", "state": "TX" },
{ "id": "2", "city": "Bloomington", "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville", "state": "WA" },
{ "id": "5", "city": "Jacksboro", "state": "TX" },
{ "id": "6", "city": "Shallowater", "state": "TX" }
];
const groupedByState =
locations.reduce((acc, { state, ...location }) => ({
...acc,
[state]: [...(acc[state] ?? []), { ...location, state }]
}), {});
console.log(groupedByState);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Django REST - JSON API results as list by key

I have a very basic API made with Django Rest Framework with an output as follows:
[
{
"name": "John",
"city": "chicago",
"age": "22"
},
{
"name": "Gary",
"city": "florida",
"age": "35"
},
{
"name": "Selena",
"city": "vegas",
"age": "18"
}
]
I want to convert it to the following format to simplify the usage of its data in charts.
{
"name": ["John", "Gary", "Selena"]
"city": ["chicago", "vegas", "florida"]
"age": ["22", "35", "18"]
}
Is there a simple way this can be done in Javascript (and Python just for curiosity)?
2. Can this be proactively solved by adjusting the Serializer or the ViewSet in DRF?
Javascript version:
const data = [
{
name: 'John',
city: 'chicago',
age: '22',
},
{
name: 'Gary',
city: 'florida',
age: '35',
},
{
name: 'Selena',
city: 'vegas',
age: '18',
},
];
const result = Object.keys(data[0]).reduce((obj, key) => {
obj[key] = data.map(_ => _[key]);
return obj;
}, {});
console.log(result);
In Python you could do it like this:
data = [
{
"name": "John",
"city": "chicago",
"age": "22"
},
{
"name": "Gary",
"city": "florida",
"age": "35"
},
{
"name": "Selena",
"city": "vegas",
"age": "18"
}
]
result = {}
for key in data[0]:
result[key] = []
for entry in data:
for key in entry:
result[key].append(entry[key])
print(result)
check this
data = [
{
"name": "John",
"city": "chicago",
"age": "22"
},
{
"name": "Gary",
"city": "florida",
"age": "35"
},
{
"name": "Selena",
"city": "vegas",
"age": "18"
}
]
output = []
name = []
city = []
age = []
for i in data:
name.append(i['name'])
city.append(i['city'])
age.append(i['age'])
output.append({"name":name,"city":city,"age":age})
print(output)

Show more items in react state when a button is clicked

I'm currently trying to create a component that show some of the state but show more once a button is clicked. Each time a button is clicked it should show 3 more items.
I tried a few different things, here is my current code: Any help and explanation is appreciated:
import React from 'react';
import { render } from 'react-dom';
class ShowSomeItems extends React.Component {
constructor() {
super()
this.state = {
cars: [
{ "name": "Audi", "country": "Germany" },
{ "name": "BMW", "country": "Germany" },
{ "name": "Chevrolet", "country": "USA" },
{ "name": "Citroen", "country": "France" },
{ "name": "Hyundai", "country": "South Korea" },
{ "name": "Mercedes-Benz", "country": "Germany" },
{ "name": "Renault", "country": "France" },
{ "name": "Seat", "country": "Spain" },
{ "name": "Dodge", "country": "USA" },
{ "name": "BMW", "country": "Germany" },
{ "name": "Tesla", "country": "USA" },
{ "name": "Volkswagen", "country": "Germany" },
{ "name": "Hyundai", "country": "South Korea" },
{ "name": "Jaguar", "country": "United Kingdom" },
{ "name": "GMC", "country": "USA" },
{ "name": "Bentley", "country": "United Kingdom" },
],
numberOfitemsShown: 5,
}
}
showMore = () => {
let numberToincrementBy = 3;
if(this.state.numberOfitemsShown < this.state.car.length){
itemsToShow = this.cars.slice(0, incremenrIndex)
numberToincrementBy+3
return itemsToShow
}
}
render() {
let itemsToShow = "Loading...";
if(this.state.numberOfitemsShown){
itemsToShow = for(let x = 0; x < 5; x++) {
<li key={x}>{this.state.cars[x]['name']}</li>
}
}
return (
<div>
<ul>
{itemsToShow}
</ul>
<button onClick={this.showMore}>
show more
</button>
</div>
);
}
}
render(<ShowSomeItems />, document.getElementById('root'));
A better approach in this case is to take advantage of component state to keep the current number of items you want to show and increment it with the button. It's cleaner and it goes well with the react way of defining UI. Example:
class ShowSomeItems extends React.Component {
constructor() {
super()
this.state = {
cars: [
{ "name": "Audi", "country": "Germany" },
{ "name": "BMW", "country": "Germany" },
{ "name": "Chevrolet", "country": "USA" },
{ "name": "Citroen", "country": "France" },
{ "name": "Hyundai", "country": "South Korea" },
{ "name": "Mercedes-Benz", "country": "Germany" },
{ "name": "Renault", "country": "France" },
{ "name": "Seat", "country": "Spain" },
{ "name": "Dodge", "country": "USA" },
{ "name": "BMW", "country": "Germany" },
{ "name": "Tesla", "country": "USA" },
{ "name": "Volkswagen", "country": "Germany" },
{ "name": "Hyundai", "country": "South Korea" },
{ "name": "Jaguar", "country": "United Kingdom" },
{ "name": "GMC", "country": "USA" },
{ "name": "Bentley", "country": "United Kingdom" },
],
numberOfitemsShown: 5,
}
}
showMore = () => {
if (this.state.numberOfitemsShown + 3 <= this.state.cars.length) {
this.setState(state => ({ numberOfitemsShown: state.numberOfitemsShown + 3 }));
} else {
this.setState({ numberOfitemsShown: this.state.cars.length })
}
}
render() {
const itemsToShow = this.state.cars
.slice(0, this.state.numberOfitemsShown)
.map(car => <li key={car.name}>{car.name}</li>);
return (
<div>
<ul>
{itemsToShow.length ? itemsToShow : "Loading..."}
</ul>
<button onClick={this.showMore}>
show more
</button>
</div>
);
}
}
EDIT
You can make the render method cleaner extracting itemsToShow into a component like this:
const Items = props => {
if (props.cars.length === 0) {
return "Loading..."
}
return props.cars
.slice(0, props.numberOfitemsShown)
.map(car => <li key={car.name}>{car.name}</li>)
}
class ShowSomeItems extends React.Component {
//rest excluded for brevity
render() {
return (
<div>
<ul>
<Items cars={this.state.cars} numberOfitemsShown={this.state.numberOfitemsShown} />
</ul>
<button onClick={this.showMore}>
show more
</button>
</div>
);
}
}
Those who require the functional component version, can check this. I have changed the class based component which #SrThompson written into a functional
import { useMemo, useState } from "react";
import "./styles.css";
const carsList = [
{ name: "Audi", country: "Germany" },
{ name: "BMW", country: "Germany" },
{ name: "Chevrolet", country: "USA" },
{ name: "Citroen", country: "France" },
{ name: "Hyundai", country: "South Korea" },
{ name: "Mercedes-Benz", country: "Germany" },
{ name: "Renault", country: "France" },
{ name: "Seat", country: "Spain" },
{ name: "Dodge", country: "USA" },
{ name: "BMW", country: "Germany" },
{ name: "Tesla", country: "USA" },
{ name: "Volkswagen", country: "Germany" },
{ name: "Hyundai", country: "South Korea" },
{ name: "Jaguar", country: "United Kingdom" },
{ name: "GMC", country: "USA" },
{ name: "Bentley", country: "United Kingdom" }
];
export default function App() {
const [cars] = useState(carsList);
const [numberOfitemsShown, setNumberOfItemsToShown] = useState(5);
const showMore = () => {
if (numberOfitemsShown + 3 <= cars.length) {
setNumberOfItemsToShown(numberOfitemsShown + 3);
} else {
setNumberOfItemsToShown(cars.length);
}
};
const itemsToShow = useMemo(() => {
return cars
.slice(0, numberOfitemsShown)
.map((car, index) => <li key={car.name + index}>{car.name}</li>);
}, [cars, numberOfitemsShown]);
return (
<div>
<ul>{itemsToShow.length ? itemsToShow : "Loading..."}</ul>
<button onClick={showMore}>show more</button>
</div>
);
}
Working codesandbox

Multidimensional sorting with underscorejs

My json structure as below;
var MyJson =
[
{
"Country": "Austria",
"SubCategory": "55",
}, {
"Country": "Brazil",
"SubCategory": "0",
}, {
"Country": "Canada",
"SubCategory": "25",
}, {
"Country": "Cyprus",
"SubCategory": "55",
}, {
"Country": "Denmark",
"SubCategory": "0",
}, {
"Country": "France",
"SubCategory": "25",
}, {
"Country": "Greece",
"SubCategory": "55",
}, {
"Country": "Hungary",
"SubCategory": "0",
}
];
I am sorting that as below;
_.sortBy(MyJson, 'SubCategory').reverse()
Result as below;
Greece : 55
Cyprus : 55
Austria : 55
France : 25
Canada : 25
Hungary : 0
Denmark : 0
Brazil : 0
My expected result as below;
Austria : 55
Cyprus : 55
Greece : 55
Canada : 25
France : 25
Brazil : 0
Denmark : 0
Hungary : 0
I have tried as below;
_.sortBy(_.sortBy(MyJson, 'SubCategory').reverse(),'Country');
is there any way to sort json as desc, asc with underscore? I am not using Lodash because of restriction of my development environment.
Thank you in advance.
Plain Javascript approach.
var data = [{ Country: "Austria", SubCategory: "55" }, { Country: "Brazil", SubCategory: "0" }, { Country: "Canada", SubCategory: "25" }, { Country: "Cyprus", SubCategory: "55" }, { Country: "Denmark", SubCategory: "0" }, { Country: "France", SubCategory: "25" }, { Country: "Greece", SubCategory: "55" }, { Country: "Hungary", SubCategory: "0" }];
data.sort(function (a, b) {
return b.SubCategory - a.SubCategory || a.Country.localeCompare(b.Country);
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using underscore as stated: you can sort twice:
_(MyJson).chain().sortBy('Country').reverse().sortBy('SubCategory').reverse().value();
This answers is what you are looking for.
Here is stated one thing from underscore docs - sortBy is a stable algorithm.
That means you can first sort by your second property to put those in the correct order, and then sort by the first property - this will leave two fields with same value for the sorted property in the same order as found. (that order you already set with the first sort)
var MyJson =
[
{
"Country": "Austria",
"SubCategory": "55",
}, {
"Country": "Brazil",
"SubCategory": "0",
}, {
"Country": "Canada",
"SubCategory": "25",
}, {
"Country": "Cyprus",
"SubCategory": "55",
}, {
"Country": "Denmark",
"SubCategory": "0",
}, {
"Country": "France",
"SubCategory": "25",
}, {
"Country": "Greece",
"SubCategory": "55",
}, {
"Country": "Hungary",
"SubCategory": "0",
}
];
var sortedArray = _(MyJson).chain().sortBy('Country').reverse().sortBy('SubCategory').reverse().value();
console.log(sortedArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>

How to loop through a nested key value pair and filter it based on a array values

I have an array which is built from the user input. I am trying to loop through a nested key value pair and check whether the values in it matches any value of the given array. The purpose is to make a search facility.
My array :
FilteredSelectedOptions=["20180211","Trax","Vienna","AN01020"]
My key value pair is :
trips = {
"20180201": [{
"journeyId": 1001,
"Number": "001",
"DriverName": "Alex",
"Transporter": {
"id": "T1",
"number": "AN01001",
"Company": "Tranzient"
},
"place": [{
"id": 001,
"value": "Washington DC"
},
{
"id": 002,
"value": "Canberra"
}
],
},
{
"journeyId": 1002,
"Number": "001",
"DriverName": "Tom",
"Transporter": {
"id": "T2",
"number": "AN01002",
"Company": "Trax"
},
"place": [{
"id": 2,
"value": "Canberra"
},
{
"id": 4,
"value": "Vienna"
}
],
},
{
"journeyId": 1003,
"Number": "004",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 1,
"value": "Washington DC",
}, {
"id": 4,
"value": "Vienna",
}],
}
],
"20180211": [{
"journeyId": 1004,
"Number": "005",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01013",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
},
{
"id": 4,
"value": "Vienna"
}
],
},
{
"journeyId": 1005,
"Number": "005",
"DriverName": "Jerry",
"Transporter": {
"id": "T3",
"number": "AN01020",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
}
],
}
],
"20180301": [{
"journeyId": 1006,
"Number": "005",
"DriverName": "demy",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
}
],
}],
};
I am expecting output like this :
trips = {
"20180201":
[{
"journeyId": 1002,
"Number": "001",
"DriverName":"Tom",
"Transporter": {
"id": "T2",
"number": "AN01002",
"Company": "Trax"
},
"place": [{"id":002,"value":"Canberra" }]
[{"id":004,"value":"Vienna"}]
},
{
"journeyId": 1003,
"Number": "004",
"DriverName":"Jack",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{"id":001,"value":"Washington DC" }]
[{"id":004,"value":"Vienna"}]
}],
"20180211": [{
"journeyId": 1004,
"Number": "005",
"DriverName":"Jack",
"Transporter": {
"id": "T3",
"number": "AN01013",
"Company": "Trax"
},
"place": [{"id":005,"value":"Bridgetown" }]
[{"id":006,"value":"Ottawa"}]
[{"id":004,"value":"Vienna"}]
},
{
"journeyId": 1005,
"Number": "005",
"DriverName": "Jerry",
"Transporter": {
"id": "T3",
"number": "AN01020",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
}
]
};
I am trying to use a for loop to check each array elements against the key value pair. What I want to do basically is
for (option in FilteredselectedOptions)
{
//logic
}
I have been able to do it for one particular array value:
const filteredTrips = Object.keys(trips).reduce((tmp, x) => {
const filtered = trips[x].filter(y => y.place && y.place.some(z => z.value === 'Vienna'));
if (filtered.length) {
tmp[x] = filtered;
}
return tmp;
}, {});
But how do I do it for all array elements irrespective of how many elements are inside array. Please help in the loop.
Just an approach by trying to filter with finding a single item in the data.
function filter(object, options) {
const check = v => options.includes(v) || v && typeof v === 'object' && Object.keys(v).some(l => check(v[l]));
var result = {};
Object.keys(object).forEach(function (k) {
var temp = options.includes(k)
? object[k]
: object[k].filter(check);
if (temp.length) {
result[k] = temp;
}
});
return result;
}
var trips = { "20180201": [{ journeyId: 1001, Number: "001", DriverName: "Alex", Transporter: { id: "T1", number: "AN01001", Company: "Tranzient" }, place: [{ id: "001", value: "Washington DC" }, { id: "002", value: "Canberra" }] }, { journeyId: 1002, Number: "001", DriverName: "Tom", Transporter: { id: "T2", number: "AN01002", Company: "Trax" }, place: [{ id: 2, value: "Canberra" }, { id: 4, value: "Vienna" }] }, { journeyId: 1003, Number: "004", DriverName: "Jack", Transporter: { id: "T3", number: "AN01003", Company: "Trax" }, place: [{ id: 1, value: "Washington DC" }, { id: 4, value: "Vienna" }] }], "20180211": [{ journeyId: 1004, Number: "005", DriverName: "Jack", Transporter: { id: "T3", number: "AN01013", Company: "Trax" }, place: [{ id: 5, value: "Bridgetown" }, { id: 6, value: "Ottawa" }, { id: 4, value: "Vienna" }] }, { journeyId: 1005, Number: "005", DriverName: "Jerry", Transporter: { id: "T3", number: "AN01020", Company: "Trax" }, place: [{ id: 5, value: "Bridgetown" }, { id: 6, value: "Ottawa" }] }], "20180301": [{ journeyId: 1006, Number: "005", DriverName: "demy", Transporter: { id: "T3", number: "AN01003", Company: "Trax" }, place: [{ id: 5, value: "Bridgetown" }, { id: 6, value: "Ottawa" }] }] },
options = ["20180211", /* "Trax", */ "Vienna", "AN01020"];
console.log(filter(trips, options));
.as-console-wrapper { max-height: 100% !important; top: 0; }
One could use recursion to search for values in an object:
function hasValue(obj, values){
for(const value of Object.values(obj)){
if(typeof value === "object"){
if(hasValue(value, values))
return true;
} else {
if(values.includes(value))
return true;
}
}
return false;
}
Now we could filter your trips by comparing the keys and using the function above:
const filteredTrips = Object.keys(trips).filter(key => {
if(FilteredSelectedOptions.includes(key))
return true;
if(hasValue(trips[key], FilteredSelectedOptions))
return true;
return false;
});
Let me know if you want a complete code.
Lets begin that objects in javascript don't have built in filter or reduce methods, only arrays do. What I would do, I would loop through the object properties, which are arrays, and check if they have one of the properties that are found in the FilteredSelectedOptions. If I find one, I will push it to a new array containing the results.

Categories