How to append value to an array only if not exists and remove it if not?
const initialArray = []; // your initial array
const add = []; // stuff you want to add
const { filtered, toAdd } = initialArray.reduce((acc, curr) => {
const index = acc.toAdd.findIndex(v => v === curr);
index === -1 ? acc.filtered.push(curr) : acc.toAdd.splice(index, 1);
return acc;
}, { filtered: [], toAdd: [...add] });
const final = [...filtered, ...toAdd];
And if your initialArray had duplicate values you could just do,
const initialArray = [...new Set(initialArrayWithDuplicates)];
Delete a value from array if exist or if no exist push it to array
you can try following code snippet
var index = list.findIndex(x => x==id)
// here you can check specific property for an object whether it exist in your array or not
if (index === -1){
list.push(id);
}
else console.log("object already exists")
Update
The problem in your code is that you are overriding the list
modifyArray(id) {
let selectedDocumentID = [];
let id = 10;
console.log('this is: ' + id);
console.log(this.selectedDocumentID);
let list = this.selectedDocumentID;
let index = list.findIndex( x => x === id);
console.log(index);
if (index !== id) {
list.push(id);
console.log(list);
this.selectedDocumentID = list;
}
else {
list.slice(list.indexOf(id));
console.log(list);
this.selectedDocumentID = list;
}
}
Array.push() if does not exist?
You could extend the Array prototype with a custom method:
// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) {
for(var i=0; i < this.length; i++) {
if(comparer(this[i])) return true;
}
return false;
};
// adds an element to the array if it does not already exist using a comparer
// function
Array.prototype.pushIfNotExist = function(element, comparer) {
if (!this.inArray(comparer)) {
this.push(element);
}
};
var array = [{ name: "tom", text: "tasty" }];
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) {
return e.name === element.name && e.text === element.text;
});
append object if not exist swift
For add(book:)
function, if the book's purchaseID
is unique, you can use contains(where:)
function to know if the Book
already exists in the Array:
func add(book: Book){
if !arrayOfBooks.contains(where: { $0.purchaseID == book.purchaseID }) {
arrayOfBooks.append(book)
}
}
or add an extension to Book
that conforms to Equatable
protocol:
extension Book: Equatable {
static func == (lhs: Book, rhs: Book) -> Bool {
return lhs.purchaseID == rhs.purchaseID
}
}
and simplify your add(book:)
function:
func add(book: Book){
if !arrayOfBooks.contains(book) {
arrayOfBooks.append(book)
}
}
For delete(book:)
function you can use removeAll(where:)
function of Array:
func delete(book: Book){
arrayOfBooks.removeAll(where: { $0.purchaseID == book.purchaseID })
}
However, as @LeoDabus said in the comments, if book ordering doesn't mater you should probably use a Set
. It will be faster on some aspects.
An implementation may be like this:
extension Book: Hashable {
static func == (lhs: Book, rhs: Book) -> Bool {
return lhs.purchaseID == rhs.purchaseID
}
func hash(into hasher: inout Hasher) {
hasher.combine(purchaseID)
}
}
class Shelf {
private let shelfName: String
private var setOfBooks = Set<Book>()
init(shelfName: String) {
self.shelfName = shelfName
}
func add(book: Book){
setOfBooks.insert(book)
}
func delete(book: Book){
setOfBooks.remove(book)
}
}
Using lodash push to an array only if value doesn't exist?
The Set
feature introduced by ES6 would do exactly that.
var s = new Set();
// Adding alues
s.add('hello');
s.add('world');
s.add('hello'); // already exists
// Removing values
s.delete('world');
var array = Array.from(s);
Or if you want to keep using regular Arrays
function add(array, value) {
if (array.indexOf(value) === -1) {
array.push(value);
}
}
function remove(array, value) {
var index = array.indexOf(value);
if (index !== -1) {
array.splice(index, 1);
}
}
Using vanilla JS over Lodash is a good practice. It removes a dependency, forces you to understand your code, and often is more performant.
Postgres append or set each elements(if not exists) of an array to an array column
I'll assume that arr_str
is of type text[]
(although you did not use the proper format for them, so I may be wrong; if that's the case, you'll need to cast your value to text[]
).
Use the following statement, if you want to remove duplications, which are already present in the arr_str
column:
update tabl1
set arr_str = (select array_agg(distinct e) from unnest(arr_str || '{b,c,d}') e)
where not arr_str @> '{b,c,d}'
Or, use the following one when you want to preserve existing duplications:
update tabl1
set arr_str = arr_str || array(select unnest('{b,c,d}'::text[]) except select unnest(arr_str))
where not arr_str @> '{b,c,d}'
Both of these statements won't touch rows, which won't be affected anyway (look at the where not arr_str @> '{b,c,d}'
predicate). This is usualy the best practice, and is almost always recommended, when triggers are involved.
http://rextester.com/GKS7382
How to add objects to array only if not exist
Hope it will help you.
// array of all active users id
NSArray* idUsersArray = [users valueForKey:@"idUser"];
// check if user already exist or not
if ([idUsersArray containsObject:u3.idUser]) {
// get index of user
NSUInteger index = [idUsersArray indexOfObject:u3.idUser];
if ([u3.active isEqualToString:@"false"]) {
[users removeObjectAtIndex:index];
NSLog(@"User leaves");
} else {
User* u = [users objectAtIndex:index];
[u setCoordinate:u3.coordinate];
NSLog(@"User changed location");
}
} else {
// add user into users array
[users arrayByAddingObject:u3];
NSLog(@"New user...");
}
Can somebody give a snippet of "append if not exists" method in swift array?
You can extend RangeReplaceableCollection
, constrain its elements to Equatable
and declare your method as mutating. If you want to return Bool in case the appends succeeds you can also make the result discardable. Your extension should look like this:
extension RangeReplaceableCollection where Element: Equatable {
@discardableResult
mutating func appendIfNotContains(_ element: Element) -> (appended: Bool, memberAfterAppend: Element) {
if let index = firstIndex(of: element) {
return (false, self[index])
} else {
append(element)
return (true, element)
}
}
}
Related Topics
Allowing/Replacing Comma as Number Separator for Input Type="Number" Using Rails
Converting String Date in React/Javascript
Remove Insignificant Trailing Zeros from a Number
How to Split a String With Multiple Separators in JavaScript
Image Taken from Camera Not Saved to Gallery
How to Pass 3 Parameters in Onclick Function .The Parameters Are Inside PHP Tag
Check If a String Is a Date Value
Allow Negative/Positive Numbers But Not Letters
Refresh Page and Keep Scroll Position
How to Select All Textframes in Document, and Retrieve the Text in Adobe Indesign
React: Do Children Always Rerender When the Parent Component Rerenders
How to Append Value to an Array Only If Not Exists and Remove It If Not
How to Wait for One Function to Finish Before Continuing
How to Check If Input Field Is in Focus or Not
How to Change the Font Color, Font Size, and Button Color in React
Split a String Only the At the First N Occurrences of a Delimiter