// 0
const obj = [{ id: 1 }, { id: 2 }, { id: 3 }];
obj.forEach((o, i) => {
if (o.id == 2) {
obj.splice(o, 1);
}
});
console.log(obj);
const arr = [
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Tom' },
{ id: 2, name: 'Nick' },
{ id: 2, name: 'Nick' },
];
// 1#
const ids = arr.map(({ id }) => id);
const unique = arr.filter(({ id }, index) =>
!ids.includes(id, index + 1));
// 2#
const unique = arr.filter((obj, index, selfArr) => {
return index === arr.findIndex(o => obj.id === o.id); // arr === selfArr
});
https://bobbyhadz.com/blog/javascript-remove-duplicates-from-array-of-objects
// 3#
const uniqueIds = [];
const unique = arr.filter(element => {
const isDuplicate = uniqueIds.includes(element.id);
if (!isDuplicate) {
uniqueIds.push(element.id);
return true;
}
return false;
});
// [{id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}]
// ✅ If you need to check for uniqueness based on multiple properties
const arr2 = [
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Nick' },
{ id: 2, name: 'Nick' },
{ id: 2, name: 'Bob' },
];
const unique2 = arr2.filter((obj, index) => {
return index === arr2.findIndex(o => obj.id === o.id && obj.name === o.name);
});
// [
// { id: 1, name: 'Tom' },
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Nick' },
// { id: 2, name: 'Bob' }
// ]
console.log(unique2);
// #4 same as 3# but with Set
const uniqueIds = new Set()
const unique = arr.filter(element => {
const isDuplicate = uniqueIds.has(element.id);
uniqueIds.add(element.id);;
if (!isDuplicate) {
return true;
}
return false;
});
// #5 same as #1
const unique = arr.filter((obj, index) => {
return index === arr.findIndex(o => obj.id === o.id);
});
// #6 same as #5 but with multiple props
const unique2 = arr2.filter((obj, index) => {
return index === arr2.findIndex(o => obj.id === o.id && obj.name === o.name);
});
// last duplicate objects
const unique = arr.filter((obj, index) => {
return index === arr.findLastIndex(o => obj.id === o.id);
});
// Map solution
const arr = [
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Nick' },
{ id: 2, name: 'James' },
];
function removeDuplicateObjects(arr, property) {
return [...new Map(arr.map(obj => [obj[property], obj])).values()];
}
// [ { id: 1, name: 'Alice' }, { id: 2, name: 'James' } ]
console.log(removeDuplicateObjects(arr, 'id'));
/* Same */
const persons= [
{ id: 1, name: 'John',phone:'23' },
{ id: 2, name: 'Jane',phone:'23'},
{ id: 1, name: 'Johnny',phone:'56' },
{ id: 4, name: 'Alice',phone:'67' },
];
const unique = [...new Map(persons.map((m) => [m.id, m])).values()];
// [
// { id: 1, name: 'Tom' },
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Nick' },
// { id: 2, name: 'James' }
// ]
console.log(removeDuplicateObjects(arr, 'name'));
console.log(unique);
const arr = [
'banan',
'apple',
'orange',
'lemon',
'apple',
'lemon',
]
// 1 no duplicities filter
function removeDuplicities(data) {
return data.filter((value, index) => data.indexOf(value) === index)
}
// 1 only duplicities filter
function onlyDuplicities(data) {
return data.filter((value, index) => data.indexOf(value) !== index)
}
// 2 set
[...new Set(arr)]
// 3 forEeach
let unique = []
arr.forEach(item => {
if (!unique.includes(item)) {
unique.push(item)
}
})
// 4 reduce #1
let unique = arr.reduce((acc, curr) => {
if (acc.indexOf(curr) < 0) {
acc.push(curr)
}
return acc
}, [])
// 4 reduce #2
let unique = arr.reduce((acc, curr) => {
return acc.includes(curr) ? acc : [...acc, curr]
}, [])
// 5 prototype #1
Array.prototype.unique = function() {
let unique = []
this.forEach((item) => {
if (!unique.includes(item)) {
unique.push(item)
}
})
return unique
}
// 5 prototype #2
Array.prototype.unique = function() {
return [...(new Set(this))] // or Array.from() instead of [...]
}
let x = [
{
id: 1,
name: 'A'
},
{
id: 2,
name: 'B'
},
{
id: 3,
name: 'C'
},
{
id: 3,
name: 'C'
},
{
id: 2,
name: 'B'
},
]
// 1
let uniqueArray = [];
let idMap = {};
for (let obj of x) {
if (!idMap[obj.id]) {
idMap[obj.id] = true;
uniqueArray.push(obj);
}
}
// 2
let uniqueArray = x.filter((obj, index, self) =>
index === self.findIndex((o) => o.id === obj.id)
);
// 3
let uniqueArray = x.reduce((accumulator, currentValue) => {
if (!accumulator.some(obj => obj.id === currentValue.id)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueArray)
sanitizedText(src) {
const div = document.createElement('div');
div.innerHTML = src;
const elements = div.querySelectorAll('*');
elements.forEach((element) => {
element.removeAttribute('style');
});
return div.innerHTML;
}
/*
vylepseny priklad o nazev pro v-model
*/
import { ref, watch } from 'vue'
export function useFormValidation(initialValue, propName = 'value') {
const value = ref(initialValue)
const error = ref('')
watch(value, (newValue) => {
if (newValue.length < 3) {
error.value = 'Value must be at least 3 characters'
} else {
error.value = ''
}
})
function validate() {
if (value.value.length < 3) {
error.value = 'Value must be at least 3 characters'
} else {
error.value = ''
}
}
return { [propName]: value, error, validate }
}
/*
https://medium.com/just-javascript-tutorials/javascript-union-intersection-and-difference-with-es6-set-13b953b21f62
*/
const setA = new Set(['🌞', '🌝', '🌎']);
const setB = new Set(['🌎', '🚀', '👩🚀']);
const union = new Set([...setA, ...setB]);
console.log(union); // Set(5) { '🌞', '🌝', '🌎', '🚀', '👩🚀' }
const intersection = new Set([...setA].filter((x) => setB.has(x)));
console.log(intersection); // Set(1) { '🌎' }
const difference = new Set([...setA].filter((x) => !setB.has(x)));
console.log(difference); // Set(2) { '🌞', '🌝' }
// Currying function for calculating the total price
function calculateTotal(price) {
return function(tax) {
return function(quantity) {
return price * quantity * (1 + tax);
};
};
}
// Create a curried function for a specific product
const calculateTotalForProduct = calculateTotal(10.99); // Set the base price
// Calculate the total price for a specific product with 8% tax and 3 quantity
const total = calculateTotalForProduct(0.08)(3);
console.log(`Total Price: $${total.toFixed(2)}`);
<template>
<div ref="el" style="height: 70px" :style="computedStyles">
<slot />
</div>
<hr />
height {{ height }}
<br />
Computed {{ computedHeight }}
<hr />
<button @click="changeHeight(150)">150</button>
<button @click="changeHeight(200)">200</button>
<button @click="changeHeight(250)">250</button>
</template>
<script>
export default {
data() {
return {
height: null,
isMounted: false,
};
},
computed: {
computedStyles() {
if (this.isMounted && this.height) return { height: this.computedHeight, background: 'limegreen' };
return { background: 'pink' };
},
computedHeight() {
if (this.isMounted && this.height) return this.height + 'px';
return null;
},
},
methods: {
changeHeight(h) {
//console.log('BEFORE', this.height);
this.height = h;
//console.log('AFTER', this.height);
},
observeElement() {
const el = this.$refs.el;
const observer = new MutationObserver(mutationsList => {
for (const mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
console.log('Element style changed:', el.style.height);
}
}
});
observer.observe(el, { attributes: true });
},
},
mounted() {
this.isMounted = true;
this.height = this.$refs.el.style.height;
this.observeElement(); // Spustíme sledování změn výšky elementu
},
};
</script>