This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 4 years ago.
Is there any method to push object to array uniquely with 1 method by ES6 ?
For Ex:
MyArray.pushUniquely(x);
Or good to use old version like ? :
MyMethod(x) {
if ( MyArray.IndexOf(x) === -1 )
MyArray.Push(x);
}
Is there any method to push uniquely by ES6 ?
Use a Set collection instead of an array.
var mySet = new Set([1, 2, 3]);
mySet.add(4);
mySet.add(3);
mySet.add(0)
console.log(Array.from(mySet))
Use includes (I've made an extension of a method so you can use it on all arrays):
Array.prototype.pushUnique(item) {
if (!this.includes(item)) this.push(item);
}
Alternatively, use a Set:
mySet.add(x); //Will only run if x is not in the Set
You can use lodash uniq method.
var uniq = _.uniq([1,2,3,4,5,3,2,4,5,1])
console.log(uniq)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
If the array is an array of objects you can do
const arr = [{
name: 'Robert',
age: 26
},
{
name: 'Joshua',
age: 69
}
]
Array.prototype.pushUniquely = function (item) {
const key = 'name';
const index = this.findIndex(i => i[key] === item[key]);
if (index === -1) this.push(item);
}
arr.pushUniquely({
name: 'Robert',
age: 24
});
console.log(arr);
If it's just an array of string or number then you can do:
Array.prototype.pushUniquely = function (item) {
if (!this.includes(item)) this.push(item);
}
Related
This question already has answers here:
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 2 years ago.
I have this code:
const arr = [
{name:"Bill", age:11},
{name:"Bill", age:11}
]
console.log(arr.includes({name:"Bill", age:11}))
Here i want to check if the array includes {name:"Bill", age:11}.
Why i get false? And how to make this checking using includes?
The includes() method compares objects by reference and not by value. In your case the three objects have three different references although they have the same properties and the same values in them.
const bill = { name: 'Bill', age: 11 }
const arr = [bill, { name: 'Jane', age: 18 }]
arr.includes(bill) // true (same reference)
arr.includes({ name: 'Bill', age: 11 }) // false (different reference)
If you want to find objects by value, you can use the find() method and pass a filter function which checks if each property of the object matches your criteria.
const arr = [{name:"Bill", age:11}, {name:"Jane", age:18}]
const exists = Boolean(arr.find(x => x.name === 'Bill' && x.age === 11))
// or even simpler using the `some()` method
const exists = arr.some(x => x.name === 'Bill' && x.age === 11)
You can create a custom array prototype method for this like includesObj
const arr = [
{name:"Bill", age:11},
{name:"Bill", age:11}
]
Array.prototype.includesObj = function(obj) {
for(let i = 0; i < this.length; i++) {
if(JSON.stringify(this[i], Object.keys(this[i]).sort()) === JSON.stringify(obj, Object.keys(obj).sort())) return true;
}
return false;
}
console.log(arr.includesObj({name: "Bill", age: 11}))
console.log(arr.includesObj({age: 11, name: "Bill"}))
console.log(arr.includesObj({name: "Bob", age: 11}))
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
can someone help me with some code to splice an array and push to new array. I have an arrays
someArray = [{
name: "Kristian",
lines: "2,5,10"
}, {
name: "John",
lines: "1,19,26,96"
}, {
name: "Kristian",
lines: "2,58,160"
}, {
name: "Felix",
lines: "1,19,26,96"
}];
i want to splice where name = to Kristian and push to a new array
You can use .reduce() method along-with .splice():
let data = [
{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"}, {name:"Felix", lines:"1,19,26,96"}
];
let result = data.reduce((r, c, i, a) => {
if(c.name = 'Kristian')
r.push(a.splice(i, 1));
return r;
}, []);
console.log(result);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use
Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Array.prototype.splice()
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
var someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John", lines:"1,19,26,96"},{name:"Kristian", lines:"2,58,160"},{name:"Felix", lines:"1,19,26,96"}];
var res = someArray.filter((p,i) => {
if(p.name=="Kristian"){
someArray.splice(i, 1); //remove the mached object from the original array
return p;
}
});
console.log(res);
console.log('----------------');
console.log(someArray);
You could use a mixture of filter and map:
const filtered = someArray.filter(obj => obj.name !== "Kristian")
const newArray = someArray.map(obj => obj.name === "Kristian")
Filtered will remove the items whilst map will create a new array with the removed items
This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 4 years ago.
I have an Array I want to remove duplicate object example bison is coming 2 times.
var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
This is what I tried
let a = beasts.indexOf(bison);
console.log(a);
But all the time it give -1 that means the object is not there at all
please ignore the values of the object
Use Array.filter and Set
Maintain a set of unique keys and if the value exists in the set, return false else add it to set and return true.
var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
let set = new Set();
let result = beasts.filter(o => {
// Get the key of object
let key = Object.keys(o)[0];
if(!set.has(key)) { // check for existence in set
// if does not exist add it to set and return true (filter IN)
set.add(key);
return true;
}
});
console.log(result);
In a simple way
const beasts = ['John', 'Paul', 'George', 'Ringo', 'John'];
let beasts = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
To do this programmatically, maintain a separate array that will hold names of processed beasts and then reduce the original array in relation to processedBeastsArray;
var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
const processedBeasts = [];
const result = beasts.reduce(function(final, current) {
const currentBeastName = Object.keys(current)[0];
if(!processedBeasts.includes(currentBeastName)){
processedBeasts.push(currentBeastName);
final.push(current);
}
return final;
}, []);
You can also use a simple forEach() loop that has O(n) complexity to get that output.
var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
var resObj = {};
beasts.forEach((beast)=>{
var key = Object.keys(beast)[0];
if(!resObj[key]){
resObj[key] = beast;
}
});
var finalArrayRes = Object.values(resObj);
console.log(finalArrayRes);
In an array of objects with diff keys, how do I find objects by key using ES6 or Lodash?
const arr = [{a:2}, {b:3}, {fred:10}]
I want the result to be:
=> [{a:2}, {fred:10}]
I don't want to use an omit style approach.
const filtered = arr.filter(obj => obj.hasOwnProperty("a") || obj.hasOwnProperty("fred"));
// or, if you have dynamic / lots of keys:
const keys = ["a", "fred"];
const filtered = arr.filter(obj => keys.some(key => obj.hasOwnProperty(key));
filter method will be useful. Create a function and pass an array of keys. Inside filter function check if the key is matching with the parameter array. If it passed then return that object
var orgObject = [{
a: 2
}, {
b: 3
}, {
fred: 10
}];
function searchByKey(keyNames) {
return orgObject.filter(function(item) {
for (var keys in item) {
if (keyNames.indexOf(keys) !== -1) {
return item
}
}
})
}
console.log(searchByKey(['a', 'fred']))
Basically you want all the objects from the array who have the fields a or fred. You can use the hasOwnProperty() on the objects while filtering.
_.filter(array, elem => elem.hasOwnProperty('a') || elem.hasOwnProperty('fred'));
This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)