1

In this array ["mac","abcde","kalman","7.4099649898408115"]

how can I get mac value is abcde and kalman value is 7.4099649898408115

I mean how can I select abcde when I want to get mac value in this string

for example

console.log(mac) // and it returns abcde 

How can I do this?

Thank you for your help

3
  • does it have to be an array? or could use an object instead? Commented Sep 3, 2020 at 6:42
  • 1
    Looks like you need an object instead of an array. Convert the array into an object literal: { mac: "abcde", kalman: "7.4099649898408115" } Commented Sep 3, 2020 at 6:42
  • I can use an object Commented Sep 3, 2020 at 6:43

4 Answers 4

2

You could convert the array to an object and take the wanted string as accessor of the object.

var data = ["mac","abcde","kalman","7.4099649898408115"],
    object = {};

for (let i = 0; i < data.length; i += 2) {
    object[data[i]] = data[i + 1];
}

console.log(object.mac);    // access with dot
console.log(object['mac']); // access with brackets and string
console.log(object.kalman);

Sign up to request clarification or add additional context in comments.

Comments

1

you can use modulo and find each even index then make the change to your object

const input = ["mac", "abcde", "kalman", "7.4099649898408115"]

const obj = {};
for (let i = 0; i < input.length; i++) {
  if (i % 2 === 0) {
    obj[input[i]] = input[i + 1]
  }
}

console.log(obj)
console.log(obj.mac)

Comments

1

Seems like your array is made out of pairs. Every even index is the key you are looking for and every odd index is the corresponding value. A better datastructure would be an object (used as an dictionary) or a map. If you want to stick with an array, you can use findIndex and then simply add one to it.

let data = ["mac","abcde","kalman","7.4099649898408115"];
let searchKey = "mac";
const index = data.findIndex(e => e === searchKey);
const result = data[index + 1];
console.log(result); // prints "abcde"

Comments

1

With reduce :

const array = ["mac","abcde","kalman","7.4099649898408115"];

const object = array.reduce((acc, cur, i, arr) => 
    !(i%2) ? {...acc, [cur]: arr[i + 1]} : acc, {})

console.log(object)
console.log('max : ', object.mac)
console.log('kalman : ', object.kalman)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.