<!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> -->
<template>
<div id="app">
<h1>{{ message }}</h1>
<div class="block">
<h4>Filter 1 - simple filter</h4>
<pre>alphaDataSource: {{ alphaDataSource }}</pre>
<button @click="simpleFilter">Find C</button>
<p>Result: {{ value }}</p>
</div>
<div class="block">
<h4>Filter 2 - remove duplicate</h4>
<pre>objectDataSource: {{ objectDataSource }}</pre>
<button @click="removeDuplicate">Remove Duplicate</button>
<p>Result: {{ value }}</p>
</div>
<div class="block">
<h4>Filter 3 - remove duplicate based on single property name</h4>
<pre>objectDataSource: {{ personDataSource }}</pre>
<button @click="findUniqeObjectBasedOnProperty">
Find Unique (based on name)
</button>
<p>Result: {{ value }}</p>
</div>
</div>
</template>
<script>
const uniqueArray = (a) =>
[...new Set(a.map((o) => JSON.stringify(o)))].map((s) => JSON.parse(s));
const uniqueArrayByProperty = (a, propertyName) => {
return Array.from(new Set(a.map((i) => i[propertyName]))).map((j) => {
return a.find((k) => k[propertyName] === j);
});
};
export default {
data() {
return {
message: "Array filter",
alphaDataSource: ["a", "b", "c", "d", "e"],
objectDataSource: [
{ id: 1, name: "Roni", roll: "123" },
{ id: 2, name: "Bob", roll: "456" },
{ id: 3, name: "Jhon", roll: "789" },
{ id: 2, name: "Bob", roll: "456" },
{ id: 3, name: "Jhon", roll: "789" }
],
personDataSource: [
{ id: 1, name: "Roni", roll: "123" },
{ id: 2, name: "Bob", roll: "456" },
{ id: 3, name: "Roni", roll: "789" },
{ id: 4, name: "Molly", roll: "101" },
{ id: 5, name: "Jolly", roll: "765" },
{ id: 6, name: "Molly", roll: "456" },
{ id: 7, name: "Molly", roll: "767" },
{ id: 8, name: "Molly", roll: "99" },
{ id: 9, name: "Bob", roll: "11" },
{ id: 10, name: "Bob", roll: "34" }
],
value: []
};
},
methods: {
simpleFilter() {
this.value = this.alphaDataSource.filter((i) => i === "c");
},
removeDuplicate() {
this.value = uniqueArray(this.objectDataSource);
},
findUniqeObjectBasedOnProperty() {
this.value = uniqueArrayByProperty(this.personDataSource, "name");
}
}
};
</script>
<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
a,
button {
color: #4fc08d;
}
button {
background: none;
border: solid 1px;
border-radius: 2em;
font: inherit;
padding: 0.75em 2em;
}
.block {
display: block;
padding: 1rem;
margin: 0.5rem;
border: 1px solid;
}
</style>
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.