push only unique elements in an array
would this accomplish what you're looking for? https://jsfiddle.net/gukv9arj/3/
x = [
{"id":"item1","val":"Items"},
{"id":"item1","val":"Items"},
{"id":"item2","val":"Items"}
];
var clickId = [];
var list = JSON.parse(x);
$.each(list, function(index, value){
if(clickId.indexOf(value.id) === -1){
clickId.push(value.id);
}
});
react push unique objects in array
You are looking for the index of false
in your array. That's because, indexOf(val[i].id === -1)
will always check indexOf(false)
which is -1. So you re-add each language.
You are probably after an algorithm more similar to this:
addLanguage = (val) => {
// Get a copy of the languages state.
const languages = [...this.state.createNewDeliveryData.languages];
for(let i=0; i< val.length; i++){
if(languages.indexOf(val[i].id) === -1) { // notice that there is a parenthesis after `id`.
languages.push(val[i].id)
}
}
this.setState({createNewDeliveryData: {languages}}); // update state and trigger re-render if there are new languages.
}
Note that you should always use setState
to mutate the state in react.
How to array_push unique values inside another array
You could foreach()
through $DocumentID
and check for the current value in $UniqueDocumentID
with in_array()
and if not present add it. Or use the proper tool:
$UniqueDocumentID = array_unique($DocumentID);
To your comment about wanting sequential keys:
$UniqueDocumentID = array_values(array_unique($DocumentID));
The long way around:
$UniqueDocumentID = array();
foreach($DocumentID as $value) {
if(!in_array($value, $UniqueDocumentID)) {
$UniqueDocumentID[] = $value;
}
}
Add only unique objects to an array in JavaScript
The Underscore findWhere
function does exactly what you need - it's not an indexOf
search by object identity, but searches objects whose properties have the same values as the input.
if (_.findWhere(shippingAddresses, toBeInserted) == null) {
shippingAddresses.push(toBeInserted);
}
How to get unique values in an array
Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains
and unique
Array.prototype.contains = function(v) { for (var i = 0; i < this.length; i++) { if (this[i] === v) return true; } return false;};
Array.prototype.unique = function() { var arr = []; for (var i = 0; i < this.length; i++) { if (!arr.contains(this[i])) { arr.push(this[i]); } } return arr;}
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];var uniques = duplicates.unique(); // result = [1,3,4,2,8]
console.log(uniques);
push object into array
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
how to make an array unique using reduce method of javascript
let arr = [];
arr.push(
{
module_id: 41,
name: 'first',
},
{
module_id: 41,
name: 'second',
important: true,
},
{
module_id: 43,
name: 'third',
}
);
const result = arr.reduce(
(acc, curr) =>
acc.find((v) => v.module_id === curr.module_id) ? acc : [...acc, curr],
[]
);
console.log(result);
How to Push Rows with Unique Values of Array into Another Array without Changing Order in Javascript
You can use .filter()
with a Set
. The Set will remove any duplicate items, so, if the size of the Set equals the size of the row then no elements were removed, which means you can keep the array in the resulting array by returning true from your .filter()
callback.
See example below:
const arr = [['A','B','C','D'],['E','F','F','G'],['1','2','3','4']];
const res = arr.filter(row => new Set(row).size === row.length);
console.log(res);
Related Topics
To Check If a String Is Alphanumeric in JavaScript
Navigationduplicated Navigating to Current Location ("/Search") Is Not Allowed
Reactjs How to Call a Component Function from Another Function on the Same File
How to Resolve Position:Fixed for a Bottom Toolbar on iOS (Iphone/Ipad)
Filereader Onload With Result and Parameter
Onchange Is Not Triggering in React Js
How to Make Mongoose Not Insert Empty Array or Object Fields into a Document
Check Whether Elements from One Array Are Present in Another Array
Ask for Geolocation Permission Again If It Was Denied
Angular 4 - Cannot Read Property Status of Null While Displaying Validation Error
How to Send One Alert from My Node.Js to My JavaScript Client
Get High-Order Block'S Id on Click
Disabled Button Onclick Event Fires
How to Pass Arguments to Addeventlistener Listener Function
How to Style Dynamically Created Elements With CSS
Google Firestore - How to Get Several Documents by Multiple Ids in One Round-Trip