Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Created December 11, 2019 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laphilosophia/4e9a82d3ec8ec8619b6e586ca986626a to your computer and use it in GitHub Desktop.
Save laphilosophia/4e9a82d3ec8ec8619b6e586ca986626a to your computer and use it in GitHub Desktop.
javascript tricks - array and objects
[...Array(10).keys()]
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
[...Array({ one:'1' }, { two: '2' }, { three: '3' }).keys()]
// [1, 2, 3]
let arr1 = [1, 2, 3]
let arr2 = [2, 3, 4]
arr1.filter(i => !arr2.includes(i))
// [1]
let arr3 = [1, 2, 3]
let arr4 = [2, 3, 4]
arr3.filter(value => arr4.indexOf(value) !== -1)
// [2, 3]
let arr5 = [
{ name: "Peter", city: "New York" },
{ name: "Jane", city: "Berlin" },
{ name: "John", city: "Berlin" }
];
arr5.reduce((res, obj) => {
res[obj.city] = res[obj.city] || []
res[obj.city].push(obj)
return res
}, {})
// {
// "New York": [{ name: "Peter", city: "New York" }],
// "Berlin": [{ name: "Jane", city: "Berlin" }, { name: "John", city: "Berlin" }]
// }
let obj = {
key1: "values1",
key2: "values2"
}
Object.entries(obj)
// [["key1", "value1"], ["key2", "value2"]]
let arr6 = [{ prop: 1}, { prop: 3}, { prop: 2}]
arr6.reduce((res, obj) => res.prop > obj.prop ? res : obj)
// 3
arr6.reduce((res, obj) => res.prop < obj.prop ? res : obj)
// 1
let obj1 = { prop1: "prop1" };
let obj2 = { prop2: "prop2" };
let merged1 = { ...obj1, ...obj2};
// or
let merged2 = Object.assign(obj1, obj2);
// { prop1: "prop1", prop2: "prop2" }
"hello".split("").map(_ => "x").join("");
// "xxxxx"
let obj = { prop: "prop" }
Object.keys(obj).map((key, i) => obj[key] + i)
// ['prop0']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment