This question already has answers here:
How to get all properties values of a JavaScript Object (without knowing the keys)?
(25 answers)
Closed 2 years ago.
I am working on this code below. I am attempting to retrieve only the values, not the keys. What this is not doing is providing me with the values but the keys. Can you help me to get this to work properly?
Unfortunately I cannot use the object.values() function, therefore I am at a loss right now. Sorry This was not stated when I posted the original.
function values(obj) {
let arr = [];
for (let value in obj) {
arr.push(value);
}
return arr;
}
let nicknames = {a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`}
let nicknameValues = values(nicknames)
console.log(nicknameValues)
You can try:
arr.push(obj[value]);
Demo:
function values(obj) {
let arr = [];
for (let value in obj) {
arr.push(obj[value]);
}
return arr;
}
let nicknames = {a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`}
let nicknameValues = values(nicknames)
console.log(nicknameValues);
Or
const result = Object.values({a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`});
console.log(result);
Demo:
const result = Object.values({a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`});
console.log(result);
You can use Object.values:
const values = Object.values({a:`Sunny`, b:`Weirdo`, c:`Chicken`,d:`Tokyo`});
console.log(values);
Or you can change you function values
arr.push(obj[value]);
Related
This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 1 year ago.
I am passing a dot separated string into function
console.log( namespace('a.b.c.d.e'))
and expect get next result
//result => "{"a":{"b":{"c":{"d":{"e":{}}}}}}"
my try (I don't know how to do it recursively)
const namespace = (string)=> {
return string.split('.').reduce((acc,el)=>{
acc[el] = {}
},{})
}
const input = "a.b.c.d.e"
const output = input.split('.').reverse().reduce((acc,el)=>{
return {[el]: acc}
},{})
console.log(output)
How about the below iteration approach :-
function namespace(input){
let result = {};
let temp = result;
const inputArr = input.split(".");
inputArr.forEach((ele)=>{
temp[ele] = {};
temp = temp[ele];
})
return result;
}
console.log( namespace('a.b.c.d.e'))
This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 2 years ago.
Here i am having two different objects :
let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}
result should be comparing this above two objects and check if the key are same , then update the oldObject value with newObject . The result has to be like this
let updatedObject = {name:"Dhanush kumar S",age:23,sex:"Male",education:"Btech"}
I tried by doing something like this, but this doesnt help. Your help is much appreciated.
const compareObjects = () => {
for (let [key,value] in oldObject) {
if (newObject.hasOwnProperty(key)) {
oldObject[newObject[key]] = newObject[value]
delete oldObject[key]; //remove old entry
}
}
console.log(oldObject)
}
compareObjects()
You can do this by using the spread syntax.
Just spread the old object first followed by the new object.
Matching keys if any would be updated by the values from the new object and new keys in the new object would be added:
let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}
const merge = (oldObj, newObj) => {
return {...oldObj, ...newObj};
}
console.log(merge(oldObject, newObject));
This question already has answers here:
How to remove item from array by value? [duplicate]
(37 answers)
Closed 4 years ago.
array["Hi","I","Hate","Love","You"];
how can I return "Hi I Love You" and delete the index "Hate".
Can I do this using Slice? From what I know if I use slice such as below:
array.slice(2,3);
It will return only "Hate" instead of getting rid of it, which is what I want.
There is very similar function (language-wise) thats doing what you need
const array = ["Hi","I","Hate","Love","You"];
array.splice(2,1);
console.log(array);
With a little upgrade, you can ask your V8 about if someone likes you or not. Just say his/her name loud and click on Run code snippet. The first response is true, you cannot repeat it for the same person.
const array = ["Hi","I","Hate","Love","You"];
let i=0;
if (Math.random() > 0.5) {
i++;
}
array.splice(2+i,1);
console.log(array);
Try the splice method:
const a = [1, 2, 3, 4]
a.splice(1, 1); // idx, count
console.log(a);
var arr = ["Hi","I","Hate","Love","You"];
var newarr = Array.prototype.concat(arr.slice(0,2), arr.slice(3));
console.log(newarr);
_.remove from lodash library will do the job.
_.remove(array, function(item) {
return item ===“Hate”;
})
https://lodash.com/docs/#remove
You can use array filter method
var org = ["Hi", "I", "Hate", "Love", "You"];
let newArray = org.filter(function(item) {
return item !== 'Hate'
});
console.log(newArray)
This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Generic solution to create an Object of unknown deepth from an Array
(1 answer)
Closed 5 years ago.
Given a JS string: var s = "deep.deeper.deepest", how can I convert this into object like this: deep: {deeper: {deepest: {}}}
const dottedToObj = (str, orig = {}) => (str.split(".").reduce((obj, key) => obj[key] = {}, orig), orig);
Just reduce the array of strings (splitted the original string) into a chain of objects. Or a bit less functional:
function dottedToObj(str){
const root = {};
var acc = root;
for(const key of str.split(".")){
acc = acc[key] = {};
}
return root;
}
A simple loop should work for this, just move through each dotted property while moving down one level in the object:
const s = "deep.deeper.deepest";
function convertToObject(str) {
const result = {};
let inner = result;
for (const key of s.split(".")) {
// Give the object a child with this key
inner[key] = {};
// Set the current object to that child.
inner = inner[key]
}
// Return the original
return result;
}
console.log(convertToObject(s))
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
In my CouchDB reduce function I need to reduce a list of items to the unique ones.
Note: In that case it's ok to have a list, it will be a small number of items of string type.
My current way is to set keys of a object, then return the keys of that object
since the place the code can't use things like _.uniq for example.
I'd like to find a more elegant way to spell it than this.
function(keys, values, rereduce) {
// values is a Array of Arrays
values = Array.concat.apply(null, values);
var uniq = {};
values.forEach(function(item) { uniq[item] = true; });
return Object.keys(uniq);
}
The best method seem to be using ES6 and Set. Single line and faster* than above according to fiddle
const myList = [1,4,5,1,2,4,5,6,7];
const unique = [...new Set(myList)];
console.log(unique);
*tested in safari
2021 answer:
const unique = (arr) => [...new Set(arr)];
unique([1, 2, 2, 3, 4, 4, 5, 1]); // [1, 2, 3, 4, 5]
Here you just create a set from the given array and then convert it back to the array.
I measured performance and it's almost twice faster now than the approach proposed in the old answer I posted before. Also, it's just a one-liner.
Updated fiddle
Old answer just for the record:
Commonly, the approach you used is a good idea.
But I could propose a solution that will make the algorithm a lot faster.
function unique(arr) {
var u = {}, a = [];
for(var i = 0, l = arr.length; i < l; ++i){
if(!u.hasOwnProperty(arr[i])) {
a.push(arr[i]);
u[arr[i]] = 1;
}
}
return a;
}
As you can see we have only one loop here.
I've made an example that is testing both your and my solutions. Try to play with it.
An alternative that's suitable for small lists would be to ape the Unix command line approach of sort | uniq:
function unique(a) {
return a.sort().filter(function(value, index, array) {
return (index === 0) || (value !== array[index-1]);
});
}
This function sorts the argument, and then filters the result to omit any items that are equal to their predecessor.
The keys-based approach is fine, and will have better performance characteristics for large numbers of items (O(n) for inserting n items into a hashtable, compared to O(n log n) for sorting the array). However, this is unlikely to be noticeable on small lists. Moreover, with this version you could modify it to use a different sorting or equality function if necessary; with hash keys you're stuck with JavaScripts notion of key equality.
This should work with anything, not just strings:
export const getUniqueList = (a: Array<any>) : Array<any> => {
const set = new Set<any>();
for(let v of a){
set.add(v);
}
return Array.from(set);
};
the above can just be reduced to:
export const getUniqueValues = (a: Array<any>) => {
return Array.from(new Set(a));
};
:)
To get unique objects, you can use JSON.stringify and JSON.parse:
const arr = [{test: "a"}, {test: "a"}];
const unique = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(unique);
Using Object.keys will give you strings if you put in integer arguments (uniq([1,2,3]) => ['1','2','3']. Here's one with Array.reduce:
function uniq(list) {
return list.reduce((acc, d) => acc.includes(d) ? acc : acc.concat(d), []);
}
This is an old question, I know. However, it is at the top of some google searches, so I wanted to add that you can combine the answers from #RobHague and #EugeneNaydenov using the following:
function unique(arr) {
const u = {};
return arr.filter((v) => {
return u[v] = !u.hasOwnProperty(v);
});
};
You can also ignore undefined values (often handy) by adding:
function unique(arr) {
const u = {};
return arr.filter((v) => {
return u[v] = (v !== undefined && !u.hasOwnProperty(v));
});
};
You can play with this solution here: https://jsfiddle.net/s8d14v5n/
I find the other answers to be rather complicated for no gain that I can see.
We can use the indexOf method of the Array to verify if an item exists in it before pushing:
const duplicated_values = ['one', 'one', 'one', 'one', 'two', 'three', 'three', 'four'];
const unique_list = [];
duplicated_values.forEach(value => {
if (unique_list.indexOf(value) === -1) {
unique_list.push(value);
}
});
console.log(unique_list);
That will work with any type of variable as well, even objects (given the identifier actually reference the same entity, merely equivalent objects are not seen as the same).
what about
function unique(list) {
for (i = 0; i<list.length; i++) {
for (j=i+1; j<list.length; j++) {
if (list[i] == list[j]) {
list.splice(j, 1);
}
}
}
}