I'm trying to obtain a list from a list in Javascript.
This is the list:
const cars = [
{
id: 1,
brand: "Mercedes Benz",
properties: [
{
property: "Mechanical",
value: 2,
},
{
property: "Chemical",
value: 2,
},
{
property: "Pressure",
value: 3,
}],
},
{
id: 2,
brand: "BMW",
properties: [
{
property: "Mechanical",
value: 5,
},
{
property: "Chemical",
value: 3,
},
{
property: "Pressure",
value: 6,
}],
}
]
I need the cars which match some properties property with a value greater than X, Y
For example, I want the cars which Mechanical properties have a value greater than 3 and a Pressure greater than 4. In that case I'll obtain the complete object with id 2.
Does anyone have an idea? That is having me a hard time
Tip: I paste it on a Node REPL ;)
This is what I tried but I obtain nothing:
cars.filter(car => car.properties.some((p1, p2) => {return ((p1.property === "Mechanical" && p1.value > 3) && (p2.property === "Pressure" && p2.value > 4))}))
Thanks in advance
You need to iterate all items and check each one for it's relevant condition, and if all items pass, return true. In your case you are checking each item for all conditions, and since no item's property can have both "Mechanical" and "Pressure" values at the same time, all fail.
When an array needs to pass all conditions, you should use Array.every() that will only return true, if all iterated items would return true.
To make this more generic, we can store the conditions as functions in an object or a Map. If there is a condition function for this property, we'll use the function to check the value. If not, we can return true immediately.
Note: this answer uses Optional chaining (?.) and the Nullish coalescing operator (??) to return true if the predicate doesn't exist. If your running environment doesn't support this operators replace the line with predicate[property] ? predicate[property](value) : true (see 2nd example).
const fn = (predicate, cars) =>
cars.filter(car => car.properties.every(({ property, value }) =>
predicate[property]?.(value) ?? true
))
const cars = [{"id":1,"brand":"Mercedes Benz","properties":[{"property":"Mechanical","value":2},{"property":"Chemical","value":2},{"property":"Pressure","value":3}]},{"id":2,"brand":"BMW","properties":[{"property":"Mechanical","value":5},{"property":"Chemical","value":3},{"property":"Pressure","value":6}]}]
const predicate = {
Mechanical: value => value > 3,
Pressure: value => value > 4,
}
const result = fn(predicate, cars)
console.log(result)
Or using a ternary:
const fn = (predicate, cars) =>
cars.filter(car => car.properties.every(({ property, value }) =>
predicate[property] ? predicate[property](value) : true
))
const cars = [{"id":1,"brand":"Mercedes Benz","properties":[{"property":"Mechanical","value":2},{"property":"Chemical","value":2},{"property":"Pressure","value":3}]},{"id":2,"brand":"BMW","properties":[{"property":"Mechanical","value":5},{"property":"Chemical","value":3},{"property":"Pressure","value":6}]}]
const predicate = {
Mechanical: value => value > 3,
Pressure: value => value > 4,
}
const result = fn(predicate, cars)
console.log(result)
I want to merge same "startime" to one (step, distance and calorie) in the list, how can I to do this.
var listNewStepData = arrayListOf<NewStepData>()
data class
data class NewStepData (
val startTime: String?,
val endTime: String?,
val step: Int? = 0,
val distance: Int? = 0,
val calorie: Int? = 0
)
this is sample
NewStepData(startTime=2020-04-14T00:00:00.000Z, endTime=2020-04-14T00:00:00.000Z, step=4433, distance=0, calorie=0)
NewStepData(startTime=2020-04-14T00:00:00.000Z, endTime=2020-04-15T00:00:00.000Z, step=0, distance=0, calorie=1697)
NewStepData(startTime=2020-04-14T00:00:00.000Z, endTime=2020-04-14T00:00:00.000Z, step=0, distance=2436, calorie=0)
NewStepData(startTime=2020-04-15T00:00:00.000Z, endTime=2020-04-15T00:00:00.000Z, step=5423, distance=0, calorie=0)
NewStepData(startTime=2020-04-15T00:00:00.000Z, endTime=2020-04-16T00:00:00.000Z, step=0, distance=0, calorie=1715)
NewStepData(startTime=2020-04-15T00:00:00.000Z, endTime=2020-04-15T00:00:00.000Z, step=0, distance=3196, calorie=0)
I want to get this
NewStepData(startTime=2020-04-14T00:00:00.000Z, endTime=2020-04-15T00:00:00.000Z, step=4433, distance=2436, calorie=1697)
NewStepData(startTime=2020-04-15T00:00:00.000Z, endTime=2020-04-16T00:00:00.000Z, step=5423, distance=3196, calorie=1715)
thanks
You can use groupBy { } for your list. It will return a map of your grouping variable type to lists of your original type. And then, use flatMap to aggregate your data.
I assume that you take maximum end date which is maxBy and sum of distances, and steps which you need sumBy for, and calories which sumByDouble is the best choice.
Here's the sample code:
var grouped = listNewStepData.groupBy { it.startTime }.flatMap { entry -> NewStepData(startTime = entry.key,
endTime = entry.value.maxBy { item -> item.endTime },
step = entry.value.sumBy { item -> item.step },
distance = entry.value.sumBy { item -> item.distance },
calorie = entry.value.sumByDouble { item -> item.calorie })
}
I have a few issues with chartjs which simple update method won't solve.
I wonder if there is an option to:
painlessly sort the datasets;
insert some data in between two points;
reload the whole chart without replacing the canvas with a
completely new chart?
There is no option built in, but it is pretty easy to write your own using the addData, removeData methods that Chart.js provides.
var MyBarChartMethods = {
// sort a dataset
sort: function (chart, datasetIndex) {
var data = []
chart.datasets.forEach(function (dataset, i) {
dataset.bars.forEach(function (bar, j) {
if (i === 0) {
data.push({
label: chart.scale.xLabels[j],
values: [bar.value]
})
} else
data[j].values.push(bar.value)
});
})
data.sort(function (a, b) {
if (a.values[datasetIndex] > b.values[datasetIndex])
return -1;
else if (a.values[datasetIndex] < b.values[datasetIndex])
return 1;
else
return 0;
})
chart.datasets.forEach(function (dataset, i) {
dataset.bars.forEach(function (bar, j) {
if (i === 0)
chart.scale.xLabels[j] = data[j].label;
bar.label = data[j].label;
bar.value = data[j].values[i];
})
});
chart.update();
},
// reload data
reload: function (chart, datasetIndex, labels, values) {
var diff = chart.datasets[datasetIndex].bars.length - values.length;
if (diff < 0) {
for (var i = 0; i < -diff; i++)
chart.addData([0], "");
} else if (diff > 0) {
for (var i = 0; i < diff; i++)
chart.removeData();
}
chart.datasets[datasetIndex].bars.forEach(function (bar, i) {
chart.scale.xLabels[i] = labels[i];
bar.value = values[i];
})
chart.update();
}
}
which you call like so (where myBarChart is your chart)
// sort
MyBarChartMethods.sort(myBarChart, 0)
// reload - same number of values
MyBarChartMethods.reload(myBarChart, 0, ["J", "F", "M", "A", "M", "J", "J"], [1, 2, 3, 4, 5, 6, 7])
// reload - more values
MyBarChartMethods.reload(myBarChart, 0, ["J", "F", "M", "A", "M", "J", "J", "A"], [1, 2, 3, 4, 5, 6, 7, 8])
// reload - less values
MyBarChartMethods.reload(myBarChart, 0, ["J", "F", "M", "A", "M"], [1, 2, 3, 4, 5])
Inserting 2 points is special case of reload, so you can use the same function (or write your own based on that easily)
Fiddle - http://jsfiddle.net/Lkdxxkfa/
I came to stackoverflow having the same question so what I have done is created a plugin that allows you to add a sort function to ChartJS
https://github.com/scotthsieh0503/chartjs-plugin-sort
it also allows you to pass in a 'pre-sorted' array as a reference for sorting
I have following list structure -
"disks" : [
{
"name" : "A",
"memberNo" :1
},
{
"name" : "B",
"memberNo" :2
},
{
"name" : "C",
"memberNo" :3
},
{
"name" : "D",
}
]
I have many elements in list and want to check for 'memberNo', if it exists
I want count of from list elements.
e.g. here count will be 3
How do I check if key exists and get count of elements from list using scala??
First create class to represent your input data
case class Disk (name : String, memberNo : String)
Next load data from repository (or other datasource)
val disks: List[Disk] = ...
And finally count
disks.count(d => Option(d.memberNo).isDefined)
In a similar fashion as in #SergeyLagutin answer, consider this case class
case class Disk (name: String, memberNo: Option[Int] = None)
where missing memberNo are defaulted with None; and this list,
val disks = List( Disk("A", Some(1)),
Disk("B", Some(2)),
Disk("C", Some(3)),
Disk("D"))
Then with flatMap we can filter out those disks with some memberNo, as follows,
disks.flatMap(_.memberNo)
res: List[Int] = List(1, 2, 3)
Namely, for the counting,
disks.flatMap(_.memberNo).size
res: Int = 3
Likewise, with a for comprehension,
for (d <- disks ; m <- d.memberNo) yield m
res: List[Int] = List(1, 2, 3)
How do I delete duplicates from a list without fooling around with a set? Is there something like list.distinct()? or list.unique()?
void main() {
print("Hello, World!");
List<String> list = ['abc',"abc",'def'];
list.forEach((f) => print("this is list $f"));
Set<String> set = new Set<String>.from(list);
print("this is #0 ${list[0]}");
set.forEach((f) => print("set: $f"));
List<String> l2= new List<String>.from(set);
l2.forEach((f) => print("This is new $f"));
}
Hello, World!
this is list abc
this is list abc
this is list def
this is #0 abc
set: abc
set: def
This is new abc
This is new def
Set seems to be way faster!! But it loses the order of the items :/
Use toSet and then toList
var ids = [1, 4, 4, 4, 5, 6, 6];
var distinctIds = ids.toSet().toList();
Result: [1, 4, 5, 6]
Or with spread operators:
var distinctIds = [...{...ids}];
I didn't find any of the provided answers very helpful.
Here is what I generally do:
final ids = Set();
myList.retainWhere((x) => ids.add(x.id));
Of course you can use any attribute which uniquely identifies your objects. It doesn't have to be an id field.
Benefits over other approaches:
Preserves the original order of the list
Works for rich objects not just primitives/hashable types
Doesn't have to copy the entire list to a set and back to a list
Update 09/12/21
You can also declare an extension method once for lists:
extension Unique<E, Id> on List<E> {
List<E> unique([Id Function(E element)? id, bool inplace = true]) {
final ids = Set();
var list = inplace ? this : List<E>.from(this);
list.retainWhere((x) => ids.add(id != null ? id(x) : x as Id));
return list;
}
}
This extension method does the same as my original answer. Usage:
// Use a lambda to map an object to its unique identifier.
myRichObjectList.unique((x) => x.id);
// Don't use a lambda for primitive/hashable types.
hashableValueList.unique();
Set works okay, but it doesn't preserve the order. Here's another way using LinkedHashSet:
import "dart:collection";
void main() {
List<String> arr = ["a", "a", "b", "c", "b", "d"];
List<String> result = LinkedHashSet<String>.from(arr).toList();
print(result); // => ["a", "b", "c", "d"]
}
https://api.dart.dev/stable/2.4.0/dart-collection/LinkedHashSet/LinkedHashSet.from.html
Try the following:
List<String> duplicates = ["a", "c", "a"];
duplicates = duplicates.toSet().toList();
Check this code on Dartpad.
If you want to keep ordering or are dealing with more complex objects than primitive types, store seen ids to the Set and filter away those ones that are already in the set.
final list = ['a', 'a', 'b'];
final seen = Set<String>();
final unique = list.where((str) => seen.add(str)).toList();
print(unique); // => ['a', 'b']
//This easy way works fine
List<String> myArray = [];
myArray = ['x', 'w', 'x', 'y', 'o', 'x', 'y', 'y', 'r', 'a'];
myArray = myArray.toSet().toList();
print(myArray);
// result => myArray =['x','w','y','o','r', 'a']
I am adding this to atreeon's answer. For anyone that want use this with Object:
class MyObject{
int id;
MyObject(this.id);
#override
bool operator ==(Object other) {
return other != null && other is MyObject && hashCode == other.hashCode;
}
#override
int get hashCode => id;
}
main(){
List<MyObject> list = [MyObject(1),MyObject(2),MyObject(1)];
// The new list will be [MyObject(1),MyObject(2)]
List<MyObject> newList = list.toSet().toList();
}
Remove duplicates from a list of objects:
class Stock {
String? documentID; //key
Make? make;
Model? model;
String? year;
Stock({
this.documentID,
this.make,
this.model,
this.year,
});
}
List of stock, from where we want to remove duplicate stocks
List<Stock> stockList = [stock1, stock2, stock3];
Remove duplicates
final ids = stockList.map((e) => e.documentID).toSet();
stockList.retainWhere((x) => ids.remove(x.documentID));
Using Dart 2.3+, you can use the spread operators to do this:
final ids = [1, 4, 4, 4, 5, 6, 6];
final distinctIds = [...{...ids}];
Whether this is more or less readable than ids.toSet().toList() I'll let the reader decide :)
For distinct list of objects you can use Equatable package.
Example:
// ignore: must_be_immutable
class User extends Equatable {
int id;
String name;
User({this.id, this.name});
#override
List<Object> get props => [id];
}
List<User> items = [
User(
id: 1,
name: "Omid",
),
User(
id: 2,
name: "Raha",
),
User(
id: 1,
name: "Omid",
),
User(
id: 2,
name: "Raha",
),
];
print(items.toSet().toList());
Output:
[User(1), User(2)]
Here it is, a working solution:
var sampleList = ['1', '2', '3', '3', '4', '4'];
//print('original: $sampleList');
sampleList = Set.of(sampleList).toList();
//print('processed: $sampleList');
Output:
original: [1, 2, 3, 3, 4, 4]
processed: [1, 2, 3, 4]
Using the fast_immutable_collections package:
[1, 2, 3, 2].distinct();
Or
[1, 2, 3, 2].removeDuplicates().toList();
Note: While distinct() returns a new list, removeDuplicates() does it lazily by returning an Iterable. This means it is much more efficient when you are doing some extra processing. For example, suppose you have a list with a million items, and you want to remove duplicates and get the first five:
// This will process five items:
List<String> newList = list.removeDuplicates().take(5).toList();
// This will process a million items:
List<String> newList = list.distinct().sublist(0, 5);
// This will also process a million items:
List<String> newList = [...{...list}].sublist(0, 5);
Both methods also accept a by parameter. For example:
// Returns ["a", "yk", "xyz"]
["a", "yk", "xyz", "b", "xm"].removeDuplicates(by: (item) => item.length);
If you don't want to include a package into your project but needs the lazy code, here it is a simplified removeDuplicates():
Iterable<T> removeDuplicates<T>(Iterable<T> iterable) sync* {
Set<T> items = {};
for (T item in iterable) {
if (!items.contains(item)) yield item;
items.add(item);
}
}
Note: I am one of the authors of the fast_immutable_collections package.
void uniqifyList(List<Dynamic> list) {
for (int i = 0; i < list.length; i++) {
Dynamic o = list[i];
int index;
// Remove duplicates
do {
index = list.indexOf(o, i+1);
if (index != -1) {
list.removeRange(index, 1);
}
} while (index != -1);
}
}
void main() {
List<String> list = ['abc', "abc", 'def'];
print('$list');
uniqifyList(list);
print('$list');
}
Gives output:
[abc, abc, def]
[abc, def]
As for me, one of the best practices is sort the array, and then deduplicate it. The idea is stolen from low-level languages. So, first make the sort by your own, and then deduplicate equal values that are going after each other.
// Easy example
void dedup<T>(List<T> list, {removeLast: true}) {
int shift = removeLast ? 1 : 0;
T compareItem;
for (int i = list.length - 1; i >= 0; i--) {
if (compareItem == (compareItem = list[i])) {
list.removeAt(i + shift);
}
}
}
// Harder example
void dedupBy<T, I>(List<T> list, I Function(T) compare, {removeLast: true}) {
int shift = removeLast ? 1 : 0;
I compareItem;
for (int i = list.length - 1; i >= 0; i--) {
if (compareItem == (compareItem = compare(list[i]))) {
list.removeAt(i + shift);
}
}
}
void main() {
List<List<int>> list = [[1], [1], [2, 1], [2, 2]];
print('$list');
dedupBy(list, (innerList) => innerList[0]);
print('$list');
print('\n removeLast: false');
List<List<int>> list2 = [[1], [1], [2, 1], [2, 2]];
print('$list2');
dedupBy(list2, (innerList) => innerList[0], removeLast: false);
print('$list2');
}
Output:
[[1], [1], [2, 1], [2, 2]]
[[1], [2, 1]]
removeLast: false
[[1], [1], [2, 1], [2, 2]]
[[1], [2, 2]]
This is another way...
final reducedList = [];
list.reduce((value, element) {
if (value != element)
reducedList.add(value);
return element;
});
reducedList.add(list.last);
print(reducedList);
It works for me.
var list = [
{"id": 1, "name": "Joshua"},
{"id": 2, "name": "Joshua"},
{"id": 3, "name": "Shinta"},
{"id": 4, "name": "Shinta"},
{"id": 5, "name": "Zaidan"}
];
list.removeWhere((element) => element.name == element.name.codeUnitAt(1));
list.sort((a, b) => a.name.compareTo(b.name));
Output:
[{"id": 1, "name": "Joshua"},
{"id": 3, "name": "Shinta"},
{"id": 5, "name": "Zaidan"}]
List<Model> bigList = [];
List<ModelNew> newList = [];
for (var element in bigList) {
var list = newList.where((i) => i.type == element.type).toList();
if(list.isEmpty){
newList.add(element);
}
}
Create method to remove duplicates from Array and return Array of unique elements.
class Utilities {
static List<String> uniqueArray(List<String> arr) {
List<String> newArr = [];
for (var obj in arr) {
if (newArr.contains(obj)) {
continue;
}
newArr.add(obj);
}
return newArr;
}
}
You can use the following way:
void main(List <String> args){
List<int> nums = [1, 2, 2, 2, 3, 4, 5, 5];
List<int> nums2 = nums.toSet().toList();
}
NOTE: This will not work if the items in the list are objects of class and have the same attributes. So, to solve this, you can use the following way:
void main() {
List<Medicine> objets = [Medicine("Paracetamol"),Medicine("Paracetamol"), Medicine("Benylin")];
List <String> atributs = [];
objets.forEach((element){
atributs.add(element.name);
});
List<String> noDuplicates = atributs.toSet().toList();
print(noDuplicates);
}
class Medicine{
final String name;
Medicine(this.name);
}
This is my solution
List<T> removeDuplicates<T>(List<T> list, IsEqual isEqual) {
List<T> output = [];
for(var i = 0; i < list.length; i++) {
bool found = false;
for(var j = 0; j < output.length; j++) {
if (isEqual(list[i], output[j])) {
found = true;
}
}
if (found) {
output.add(list[i]);
}
}
return output;
}
Use it like this:
var theList = removeDuplicates(myOriginalList, (item1, item2) => item1.documentID == item2.documentID);
or...
var theList = removeDuplicates(myOriginalList, (item1, item2) => item1.equals(item2));
or...
I have a library called Reactive-Dart that contains many composable operators for terminating and non-terminating sequences. For your scenario it would look something like this:
final newList = [];
Observable
.fromList(['abc', 'abc', 'def'])
.distinct()
.observe((next) => newList.add(next), () => print(newList));
Yielding:
[abc, def]
I should add that there are other libraries out there with similar features. Check around on GitHub and I'm sure you'll find something suitable.