I have an array of objects containing world countries with some additional information e.g.
countries = [
{
flag: 'assets/flags/angola.svg',
code: 'AGO',
name: 'Angola',
regions: [{
name: 'Luanda'
}]
},
{
flag: 'assets/flags/albania.svg',
code: 'ALB',
name: 'Albania',
regions: [{
name: 'Korça'
}, {
name: 'Tirana'
}, {
name: 'Gjirokastër'
}]
}...
I want to extract three of my favorite countries into a new array while removing them from the original array so I end up with two arrays one for my favorite countries and one for the rest of the countries.
I managed to achieve this the following way:
public createCountriesList(allCountries: Country[]) {
let topCountries: Country[] = [];
let restOfCountries: Country[];
allCountries.forEach((element) => {
switch (element.code) {
case 'HRV':
topCountries.push(element);
break;
case 'AT':
topCountries.push(element);
break;
case 'GER':
topCountries.push(element);
break;
}
});
restOfCountries = allCountries.filter((c) => {
return !topCountries.includes(c);
});}
It works, but I was wondering if there is a more elegant way to do this?
Everything seems fine according to me...
Obviously you need two arrays one for the extracted ones and second for rest of countries.
One thing we can work on is the switch case.
Instead of switch case you can use .includes function.
Store the name of countries you want to extract in an array.
const arr = ['HRV','AT','GR']
now you can do,
if(arr.includes(element.code)){
//push into new array
} else{
//push into another
}
One more thing you can do is save restOfTheCountries using .filter function.
Just return true for the countries which fails your above if case.
You can just use regular filter to split the array:
const isTop = ({code}) => ['HRV','AT','GR'].includes(code);
const topCountries = allCountries.filter(isTop);
const restOfCountries = allCountries.filter((contry) => !isTop(contry));
Another way, you can add a property that shows whether this country is top or not, and filter by this key
const withTop = countries.map((e) => ({...e, top: ['AGO','AT','GR'].includes(e.code)}));
// {
// code: "AGO"
// flag: "assets/flags/angola.svg"
// name: "Angola"
// regions: [{…}]
// top: true
// }
I would probably create a separate generic function for splitting array based on the criteria (using ts since you are)
const splitArray = <T>(array: Array<T>, matchFunction: (el: T) => boolean) => {
const matching: T[] = [], nonMatching: T[] = []
array.forEach(el => matchFunction(el) ? matching.push(el) : nonMatching.push(el))
return [matching, nonMatching]
}
then you can call it with the array and a function
const [topCountries, restOfCountries] = splitArray(countries, c => ["HRV", "AT", "GER"].includes(c.code))
that would be a bit more readable. a more elegant solution is to extend Array with that functionality (Array.prototype.split) then using countries.split(c => ["HRV", "AT", "GER"].includes(c.code))
All suggestions so far seem valid, I ended up using #Alexandr Belan answer as it was the most straightforward to implement in my case, I don't know why I used switch case instead of filter like for the topCountries 🤷♂️. Final code (added alphabetical sorting of the countries as well)
const suggestedCountriesList = ['Brazil', 'France', 'Germany'];
const suggested = ({ name }) => suggestedCountriesList.includes(name);
const suggestedCountries = allCountries.filter(suggested);
const otherCountries = allCountries.filter((country) => !suggested(country));
// sort alphabetically
otherCountries.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
suggestedCountries.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
return [suggestedCountries, otherCountries];
Related
Suppose there is an array like this:
const a = [ {p:1}, {p:2}, {p:3} ];
Is it possible to destructure this array in order to obtain p = [1, 2, 3] ?
Because this does not work :
const [ ...{ p } ] = a; // no error, same as const p = a.p;
// p = undefined;
Edit
In response to all the answers saying that I need to use Array.prototype.map, I am aware of this. I was simply wondering if there was a way to map during the destructuring process, and the answer is : no, I need to destructure the array itself, then use map as a separate step.
For example:
const data = {
id: 123,
name: 'John',
attributes: [{ id:300, label:'attrA' }, { id:301, label:'attrB' }]
};
function format(data) {
const { id, name, attributes } = data;
const attr = attributes.map(({ label }) => label);
return { id, name, attr };
}
console.log( format(data) };
// { id:123, name:'John', attr:['attrA', 'attrB'] }
I was simply wondering if there was a way, directly during destructuring, without using map (and, respectfully, without the bloated lodash library), to retrive all label properties into an array of strings.
Honestly I think that what you are looking for doesn't exist, normally you would map the array to create a new array using values from properties. In this specific case it would be like this
const p = a.map(element => element.p)
Of course, there are some packages that have many utilities to help, like Lodash's map function with the 'property' iteratee
you can destructure the first item like this :
const [{ p }] = a;
but for getting all values you need to use .map
and the simplest way might be this :
const val = a.map(({p}) => p)
Here's a generalized solution that groups all properties into arrays, letting you destructure any property:
const group = (array) => array.reduce((acc,obj) => {
for(let [key,val] of Object.entries(obj)){
acc[key] ||= [];
acc[key].push(val)
}
return acc
}, {})
const ar = [ {p:1}, {p:2}, {p:3} ];
const {p} = group(ar)
console.log(p)
const ar2 = [{a:2,b:1},{a:5,b:4}, {c:1}]
const {a,b,c} = group(ar2)
console.log(a,b,c)
I am using eslint and getting this error.
Expected to return a value in arrow function
The error is showing on the third line of the code.
useEffect(() => {
let initialPrices = {};
data.map(({ category, options }) => {
initialPrices = {
...initialPrices,
[category]: options[0].price,
};
});
setSelectedPrice(initialPrices);
}, []);
The map function must return a value. If you want to create a new object based on an array you should use the reduce function instead.
const reducer = (accumulator, { category, options }) => (
{...accumulator, [category]:options[0].price}
)
const modifiedData = data.reduce(reducer)
More information https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
The map function is intended to be used when you want to apply some function over every element of the calling array. I think here it's better to use a forEach:
useEffect(() => {
let initialPrices = {};
data.forEach(({ category, options }) => {
initialPrices = {
...initialPrices,
[category]: options[0].price,
};
});
setSelectedPrice(initialPrices);
}, []);
Your map function should return something. Here it's not the case so the error happens. Maybe a reduce function will be more appropriate than map?
From what I can see in your case, is that you want to populate initialPrices, and after that to pass it setSelectedPrice. The map method is not a solution, for you in this case, because this method returns an array.
A safe bet in your case would a for in loop, a forEach, or a reduce function.
const data = [
{
category: "ball",
options: [
{
price: "120.45"
}
]
},
{
category: "t-shirt",
options: [
{
price: "12.45"
}
]
}
];
The forEach example:
let initialPrices = {};
// category and options are destructured from the first parameter of the method
data.forEach(({ category, options}) => {
initialPrices[category] = options[0].price;
});
// in this process I'm using the Clojure concept to add dynamically the properties
setSelectedPrice(initialPrices);
The reduce example:
const initialPrices = Object.values(data).reduce((accumulatorObj, { category, options}) => {
accumulatorObj[category] = options[0].price
return accumulatorObj;
}, {});
setSelectedPrice(initialPrices);
Okay, so I am trying to create a function that allows you to input an array of Objects and it will return an array that removed any duplicate objects that reference the same object in memory. There can be objects with the same properties, but they must be different in-memory objects. I know that objects are stored by reference in JS and this is what I have so far:
const unique = array => {
let set = new Set();
return array.map((v, index) => {
if(set.has(v.id)) {
return false
} else {
set.add(v.id);
return index;
}
}).filter(e=>e).map(e=>array[e]);
}
Any advice is appreciated, I am trying to make this with a very efficient Big-O. Cheers!
EDIT: So many awesome responses. Right now when I run the script with arbitrary object properties (similar to the answers) and I get an empty array. I am still trying to wrap my head around filtering everything out but on for objects that are referenced in memory. I am not positive how JS handles objects with the same exact key/values. Thanks again!
Simple Set will do the trick
let a = {'a':1}
let b = {'a': 1,'b': 2, }
let c = {'a':1}
let arr = [a,b,c,a,a,b,b,c];
function filterSameMemoryObject(input){
return new Set([...input])
}
console.log(...filterSameMemoryObject(arr))
I don't think you need so much of code as you're just comparing memory references you can use === --> equality and sameness .
let a = {'a':1}
console.log(a === a ) // return true for same reference
console.log( {} === {}) // return false for not same reference
I don't see a good reason to do this map-filter-map combination. You can use only filter right away:
const unique = array => {
const set = new Set();
return array.filter(v => {
if (set.has(v.id)) {
return false
} else {
set.add(v.id);
return true;
}
});
};
Also if your array contains the objects that you want to compare by reference, not by their .id, you don't even need to the filtering yourself. You could just write:
const unique = array => Array.from(new Set(array));
The idea of using a Set is nice, but a Map will work even better as then you can do it all in the constructor callback:
const unique = array => [...new Map(array.map(v => [v.id, v])).values()]
// Demo:
var data = [
{ id: 1, name: "obj1" },
{ id: 3, name: "obj3" },
{ id: 1, name: "obj1" }, // dupe
{ id: 2, name: "obj2" },
{ id: 3, name: "obj3" }, // another dupe
];
console.log(unique(data));
Addendum
You speak of items that reference the same object in memory. Such a thing does not happen when your array is initialised as a plain literal, but if you assign the same object to several array entries, then you get duplicate references, like so:
const obj = { id: 1, name: "" };
const data = [obj, obj];
This is not the same thing as:
const data = [{ id: 1, name: "" }, { id: 1, name: "" }];
In the second version you have two different references in your array.
I have assumed that you want to "catch" such duplicates as well. If you only consider duplicate what is presented in the first version (shared references), then this was asked before.
I'm trying to create a conditional sub-set of an array.
I have an array allBooks which has properties such as type,author,id etc.
In a particular view I want to show only some of properties based on a condition.
For example; displaying summarized properties of all the books in stock.
Here is what I have tried:
let booksInStock: any[] = [];
this.allBooks.forEach(book => {
// Add only when book is in stock
if (book.isInStock) {
// Get only few keys from all the available keys
let temp: any = {
typeOfBook: book.targetType,
author: book.author,
bookId: book.id,
bookDisplayName: book.value,
bookName: book.bookName
};
// Add to the summarized or filtered list
booksInStock.push(temp);
}
});
Is there a more efficient way of doing it?
Using filter and map would be more semantic, like so:
let booksInStock = this.allBooks
.filter(book => book.isInStock)
.map(book => ({
typeOfBook: book.targetType,
author: book.author,
bookId: book.id,
bookDisplayName: book.value,
bookName: book.bookName
})
);
If efficiency is your priority however, a for loop is faster. See this link for an example: https://jsperf.com/map-vs-for-loop-performance/6
For example:
// This function is pretty generic, you can find one in e.g. underscore.js or Ramda:
const pluck = fields => item =>
Object
.keys(item)
.filter(key => fields.includes(key))
.reduce((result, key) => {
result[key] = item[key]
return result
}, {})
// Create filter+map+pluck -settings for different 'views':
const inStock = books =>
books.filter(b => b.isInStock)
.map(pluck(['targetType', 'author', 'id', 'value', 'name']))
// Invoke them:
const booksInStock = inStock([
{ isInStock: true, author:'harry', otherFIeld:'not-included' },
{ isInStock:false, author:'notharry'}
])
I have a dictionary named CarValues in my code which contains following data:
CarValues is a dictionary initialized in the state.
dictionary: CarValues
key ==> string
Value ==> Array
key => Honda, Value => white, yellow, red, orange
key => Toyota, Value => white, yellow, green, black
Key => Volkswagen Value => 123, 456, 343
I would like to delete Honda and its value completely from CarValues. Though, I see few similar questions, I couldn't find the best solution for this question.
How can I remove an attribute from a Reactjs component's state object
This should solve your issue
yourMethod(key) {
const copyCarValues= {...this.state.CarValues}
delete copyCarValues[key]
this.setState({
CarValues: copyCarValues,
})
}
I believe in order to truly do this without mutating the state, you will need to re-create the entire state like so.
class Test extends React.Component {
state = {
thingToDelete: {},
otherStuff: {}
};
deleteThingToDelete = () => {
const {thingToDelete, ...state} = this.state;
this.setState(state);
}
}
Using the spread operator, we achieve a shallow clone, so be wary about that. The other option is to use Object.assign but that will also only offer a shallow clone but you will achieve much better browser support.
Probably arriving here a bit late, but here is a way of doing this with hooks and without actually mutating the previous state.
const sampleItems = {
'key1': { id: 1, name: 'test'},
'key2': { id: 2, name: 'test2'},
}
const Test = props => {
const [items, setItems] = useState(sampleItems);
deleteItemFromStateObject = itemKey => {
setItems(({[itemKey]: toDelete, ...rest}) => rest);
}
}
The easiest way to do this would be:
const carValues = Object.assign({}, this.state.carValues)
delete carValues[key]
this.setState({ carValues })
You can use Underscore.js or Lodash http://underscorejs.org/#omit
_.omit(copyCarValues, 'Honda');
First Initialise Array Globally
var dict = []
Add Object into Dictionary
dict.push(
{ key: "One",value: false},
{ key: "Two",value: false},
{ key: "Three",value: false});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: false},
2: {key: "Three", value: false}]
Update Object from Dictionary
Object.keys(dict).map((index) => {
if (index == 1){
dict[index].value = true
}
});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: true},
2: {key: "Three", value: false}]
Delete Object from Dictionary
Object.keys(dict).map((index) => {
if (index == 2){
dict.splice(index)
}
});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: true}]
Here is another simple enough solution to achieve this.
const myCarsValueInState = this.state.myCarsValueInState;
Object.keys(myCarsValueInState).map((index) => {
myCarsValueInState[index] = undefined; // you can update on any condition if you like, this line will update all dictionary object values.
return myCarsValueInState;
});
Simple enough.