find array value that index matches another array values [duplicate] - javascript

This question already has answers here:
How to select elements from an array based on the indices of another array in JavaScript?
(3 answers)
Closed 2 years ago.
I have the following 2 arrays
tokenIds = [0,1,3]
and
strings = ["hello", "foo", "goodbye", "bar"]
what would be the best way to create a new array with the elements in "strings" array which index's match the values of "tokenIds" array?
Such as creating a new array like the following
newstrings = ["hello", "foo", "bar"]
I have tried the following:
const newstrings = strings.filter(index => tokenIds.includes(tokenIds.index));
Thanks in advance!

Just map the tokenIds array:
const newstrings = tokenIds.map(i => strings[i]);

const tokenIds = [0,1,3]
const strings = ["hello", "foo", "goodbye", "bar"]
const result = strings.filter((str,idx) => tokenIds.includes(idx))
console.log(result)

May not be the best way to do it, but produces the result you require.
tokenIds = [0,1,3]
strings = ["hello", "foo", "goodbye", "bar"]
newstrings = []
for(var id in tokenIds)
{
newstrings.push(strings[tokenIds[id]]);
}
console.log(newstrings);

Related

javascript: create dictionary from array of key-values objects [duplicate]

This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Merge multiple objects inside the same array into one object [duplicate]
(2 answers)
How to concatenate properties from multiple JavaScript objects
(14 answers)
Closed 1 year ago.
I have an array of objects.
const ar = [ {0 : "A"}, {1 : "B"}];
I want to create an dictionary from it
const di = {0 : "A", 1 : "B"};
I am a little struggling with this conversion. How it is possible to do it using map or reduce?
const di = ar.map( ob => (???) }
A simple reduce can be used to merge all objects. Be aware that the keys need to be unique otherwise you will overwrite them.
The merging is done with the spread syntax
const ar = [{0 : "A"}, {1 : "B"}];
const di = ar.reduce((acc, obj) => ({...acc, ...obj}));
console.log(di);
Another simple approach is the use of Object.assign
const ar = [{0 : "A"}, {1 : "B"}];
const di = Object.assign({}, ...ar);
console.log(di);
You should use reduce here instead of map. map will give you an array of objects but what you need is an object will all keys. So reduce is the best tool for it.
Main difference between map and reduce
const ar = [{ 0: "A" }, { 1: "B" }];
const di = { 0: "A", 1: "B" };
const result = ar.reduce((acc, curr) => {
Object.keys(curr).forEach((k) => (acc[k] = curr[k]));
return acc;
}, {});
console.log(result);

Combine items after mapping from an array to a single object [duplicate]

This question already has answers here:
Flatten array with objects into 1 object
(12 answers)
Closed 2 years ago.
Can you please help me to create object out of array of objects?
Array to convert arr = [{name:'Ryan'}, {surname:'raynold'}]
required output finalObj = {name:ryan, surname:raynold}
I tried to get the result by doing
let objectArr = Object.assign({}, arr);
but result was like this
{ 0: {shoulder: "14"}, 1:{neck: ""} }
This is a good case for Object.assign.
let arr = [{name:'Ryan'}, {surname:'raynold'}]
let finalObj = Object.assign({}, ...arr);
console.log(finalObj);
Object.assign can take multiple objects as arguments, and so you can spread those objects from your input array. The first argument represents the object in which the others are merged.
You could do it with a array reduce like this:
let finalObj = arr.reduce((acc, cur) => ({...acc, ...cur}), {})

How can I create keys for an array in Javascript? [duplicate]

This question already has answers here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Convert array of strings to objects and assign specific key
(1 answer)
Closed 3 years ago.
I would like to know how can I create keys for an array of values in javascript like this?
const array = ["NodeJs", "Javascript", "React"]
and transform it like this
const array = [{"name": "NodeJs"}, {"name": "Javascript"}, {"name": "React"}]
Using Array.prototype.map:
const arr = ["NodeJs", "Javascript", "React"];
const newArr = arr.map(name => ({name})); // or arr.map(item => ({name: item}))
console.log(newArr);
You can also do it using Array.from(iterable, mappingFunction) which will return a new array with objects {name: name}:
const array = ["NodeJs", "Javascript", "React"];
const mapArray = Array.from(array, (name) => ({name}));
console.log(mapArray);

Convert array to object keys [duplicate]

This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)

JS: Convert An Array Into An Object Without Indexes [duplicate]

This question already has answers here:
Return object with default values from array in Javascript
(4 answers)
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 4 years ago.
What's the best way to convert an array, to an object with those array values as keys, empty strings serve as the values of the new object.
['a','b','c']
to:
{
a: '',
b: '',
c: ''
}
try with Array#Reduce
const arr = ['a','b','c'];
const res = arr.reduce((acc,curr)=> (acc[curr]='',acc),{});
console.log(res)
You can use Array.prototype.reduce()and Computed property names
let arr = ['a','b','c'];
let obj = arr.reduce((ac,a) => ({...ac,[a]:''}),{});
console.log(obj);
const target = {}; ['a','b','c'].forEach(key => target[key] = "");
You can use Object.assign property to combine objects created with a map function, please take into account that if values of array elements are not unique the latter ones will overwrite previous ones
const array = Object.assign({},...["a","b","c"].map(key => ({[key]: ""})));
console.log(array);
You can use array reduce function & pass an empty object in the accumulator. In this accumulator add key which is denoted by curr
let k = ['a', 'b', 'c']
let obj = k.reduce(function(acc, curr) {
acc[curr] = '';
return acc;
}, {});
console.log(obj)

Categories

Resources