filter Object of arrays JavaScript [duplicate] - javascript

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 3 years ago.
Let's say I have this Object of arrays:
foo = {morning: [1,2,3,4,5], afternoon: [1,2,3,4,7]}
I want to write a function that returns this object but remove a particular value.
ex: I want to remove the number 3 in afternoon.
The function would return {morning: [1,2,3,4,5], afternoon: [1,2,4,7]}
myFunction = (partsOfDay, number) => {
// do something
// returns the object of arrays but without the specified value
}
How can I do that ?

You can do this without changing the source object using Array.reduce() and Object.entries().
The properties of the returned object will still point to the source object but the filtered array properties will be copied with Array.filter().
const foo = { morning: [1,2,3,4,5], afternoon: [1,2,3,4,7] };
const myFilter = (obj, prop, value) => Object.entries(obj).reduce((acc, [key, val]) => {
acc[key] = key === prop && Array.isArray(val) ? val.filter(x => x !== value) : val;
return acc;
}, {});
console.log(myFilter(foo, 'afternoon', 3));
console.log(myFilter(foo, 'morning', 3));
console.log(foo);

There are many ways, something like this
var partsOfDay = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
myFunction = (partsOfDay, number) => {
var filtered = partsOfDay.filter(function(value, index, arr){
return value != number;
});
}
Refer for more here

Related

Sort by values but alphabetical order when values are same in Javascript [duplicate]

This question already has answers here:
How can I sort a javascript array of objects numerically and then alphabetically? [duplicate]
(5 answers)
Closed last month.
If I have the object,
const obj = { Peter: 3, Jeremy: 2, Chris: 1, Adam: 2 };
I want to compare object values, and sort them in a numerical order.
Therefore, I tried
let answer = Object.keys(obj);
answer.sort((a,b) => {
return obj[b] - obj[a];
})
The output is ['Peter', 'Jeremy', 'Adam', 'Chris'].
I want to sort Jeremy and Adam in Alphabetical order as they have same values.
The output I want is ['Peter', 'Adam', 'Jeremy', 'Chris']
How do I approach to this answer?
you can use a condition for case where values are same to sort based on alphabetical order of keys
const obj = { Peter: 3, Jeremy: 2, Chris: 1, Adam: 2 };
let answer = Object.keys(obj);
answer.sort((a,b) => {
if (obj[b] == obj[a]) return a.localeCompare(b)
return obj[b] - obj[a];
})
console.log(answer)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
const obj = { Peter: 3, Jeremy: 2, Chris: 1, Adam: 2 };
const result = Object.entries(obj) // get array of [key, value]
// sort by value descending, then alphabetically by key
.sort(([a,b],[c,d])=>d-b || a.localeCompare(c))
.map(([i])=>i) // extract just the key
console.log(result)

In JS map() method, why can't callback function parameters compute with each other? [duplicate]

This question already has answers here:
Array map function doesn't change elements
(4 answers)
Why does this map function not mutate the values in the original array?
(3 answers)
Closed 2 years ago.
The problem is that I cannot subtract each index of an array from its element(number), using the array.prototype.map() method. I expected the subtraction to be valid, but it is not.
Here is the code:
const whiteSp = [ 5, 11 ];
whiteSp.map(function (ele, i) {
console.log(ele, i) // 5 0, 11 1
console.log(ele - i) // 5, 10
ele = ele - i;
return ele;
});
console.log(whiteSp) // expected [ 5, 10 ], but got [ 5, 11 ]
The second console.log indicates the computation has been made as seen by the value 10, but returns 11 for some reason.
I have also tried 'return ele - i' without its above line, but still does not work.
Ciao, you could try something like this:
let whiteSp = [ 5, 11 ];
whiteSp = whiteSp.map((ele, i) => { return ele - i; });
console.log(whiteSp)
and remember that map function returns a new array so you have to do whiteSp = whiteSp.map....
You need an assignment of the mapped values.
const
whiteSp = [5, 11],
result = whiteSp.map((ele, i) => ele - i);
console.log(result);

Filter javascript map object by array of keys [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have an array of keys:
var arr = ['var1', 'var2', 'var3']
I also have a Javascript map object containing four keys (var1, var2, var3, var4) and values (1, 2, 3, 4) which I want to filter by the arr-array so I get a new map object only containing the keys (var1, var2, var3) and values (1, 2, 3). Does anyone know how I can do this?
You can populate a new object using reduce (1):
var map = {a: 1, b: 2, c: 3};
var keys = ["b", "c", "d"];
var c = keys.reduce(function(obj, key) {
if (map.hasOwnProperty(key)) obj[key] = map[key];
return obj;
}, {}); // {b: 2, c: 3}
You have to use delete operator in order to remove one object' property.
var arr = ['var1', 'var2', 'var3']
var obj = { var1:1, var2:2, var3:3, var4:4};
var newObj = Object.assign({}, obj);
Object.keys(newObj).forEach(function(key){
if(!arr.includes(key))
delete newObj[key];
});
console.log(newObj);
If I am not mistaken, you have the following situation :
const keysToKeep = ["var1", "var2", "var3"];
const object = {
"var1": 1,
"var2": 2,
"var3": 3
};
If that is the case then you can do the following :
const filtered = Object.entries(object)
.filter(e => keysToKeep.includes(e[0]))
.reduce((acc, entrt)=>{
acc[entry[0]] = entry[1];
return acc;
}, {});
Or
const filtered = Object.entries(object)
.map(e => ({
"key": e[0],
"value": e[1]
})).filter(e => keysToKeep.includes(e.key))
.reduce((acc, entry)=>{
acc[entry.key] = entry.value;
return acc;
}, {});
This will basically take each entry contained in the object, only keep the entries that have a key that is in the array of keys defined earlier and then reduce it back to an object.

Typescript - Keep only specific object keys [duplicate]

This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 5 years ago.
I have an object with some keys
{
a: 1,
b: 2,
c: 3,
.....
}
I'm looking for the easiest way to keep only specific keys from the object
For example I want to clone this object and keep only "a" and "b"
The first object doesn't have specific keys, so I can't just delete "c"
I'm looking for the easiest way
Thanks
You can use .reduce on Array of keys (as strings).
You can check for .hasOwnProperty to validate the existing of the key before adding it to the new object.
Example:
const obj = {
a: 1,
b: 2,
c: 3,
}
const newObj = ['a', 'c', 'z'].reduce((result, key) => {
if (obj.hasOwnProperty(key)) {
result[key] = obj[key];
}
return result;
}, {});
console.log(newObj)

array.push is not a function - when working with reduce [duplicate]

This question already has answers here:
Why can't direcrlty return a value by using .push() in javascript?
(2 answers)
Closed 5 years ago.
Can someone please help me understand whats going on here?
let firstArray = [];
firstArray.push(1);
firstArray.push(1);
firstArray.push(1);
console.log("firstArray", firstArray); // result [ 1, 1, 1 ] - as expected.
let secondArray = [1, 2, 3].reduce((acc, item) => {
console.log("acc", acc);
console.log("typeof acc", typeof acc);
// on first passing, the accumulator (acc) is Array[] == object.
// on the second passing the acc == number.
// but why?
/// i expect to get [1,1,1] as my secondArray.
return acc.push(1);
}, []);
console.log("secondArray", secondArray);
the program crashes with "acc.push is not a function"
And inspecting the first logged accumulator shows that we have the push method - it's a real function:
The return value of Array#push is the new length of the array after the push. This means that in the second iteration acc is a number, which doesn't have the push method.
The fix is simple - separate the push and return statements:
const secondArray = [1, 2, 3].reduce((acc, item) => {
acc.push(1);
return acc;
}, []);
console.log(secondArray);

Categories

Resources